Supply and DemandThis is a "Supply and Demand" script designed to help traders spot potential levels of supply (resistance) and demand (support) in the market by identifying pivot points from past price action.
Differences from Other Scripts:
Unlike many pivot point scripts, this one offers a greater degree of customization and flexibility, allowing users to determine how many ranges of pivot points they wish to plot (up to 10), as well as the number of the most recent ranges to display.
Furthermore, it allows users to restrict the plotting of pivot points to specific timeframes (15 minutes, 30 minutes, 1 hour, 4 hours, and daily) using a toggle input. This is useful for traders who wish to focus on these popular trading timeframes.
This script also uses the color.new function for a more transparent plotting, which is not commonly used in many scripts.
How to Use:
The script provides two user inputs:
"Number of Ranges to Plot (1-10)": This determines how many 10-bar ranges of pivot points the script will calculate and potentially plot.
"Number of Last Ranges to Show (1-?)": This determines how many of the most recent ranges will be displayed on the chart.
"Limit to specific timeframes?": This is a toggle switch. When turned on, the script only plots pivot points if the current timeframe is one of the following: 15 minutes, 30 minutes, 1 hour, 4 hours, or daily.
The pivot points are plotted as circles on the chart, with pivot highs in red and pivot lows in green. The transparency level of these plots can be adjusted in the script.
Market and Conditions:
This script is versatile and can be used in any market, including Forex, commodities, indices, or cryptocurrencies. It's best used in trending markets where supply and demand levels are more likely to be respected. However, like all technical analysis tools, it's not foolproof and should be used in conjunction with other indicators and analysis techniques to confirm signals and manage risk.
A technical analyst, or technician, uses chart patterns and indicators to predict future price movements. The "Supply and Demand" script in question can be an invaluable tool for a technical analyst for the following reasons:
Identifying Support and Resistance Levels : The pivot points plotted by this script can act as potential levels of support and resistance. When the price of an asset approaches these pivot points, it might bounce back (in case of support) or retreat (in case of resistance). These levels can be used to set stop-loss and take-profit points.
Timeframe Analysis : The ability to limit the plotting of pivot points to specific timeframes is useful for multiple timeframe analysis. For instance, a trader might use a longer timeframe to determine the overall trend and a shorter one to decide the optimal entry and exit points.
Customization : The user inputs provided by the script allow a technician to customize the ranges of pivot points according to their unique trading strategy. They can choose the number of ranges to plot and the number of the most recent ranges to display on the chart.
Confirmation of Other Indicators : If a pivot point coincides with a signal from another indicator (for instance, a moving average crossover or a relative strength index (RSI) divergence), it could provide further confirmation of that signal, increasing the chances of a successful trade.
Transparency in Plots : The use of the color.new function allows for more transparent plotting. This feature can prevent the chart from becoming too cluttered when multiple ranges of pivot points are plotted, making it easier for the analyst to interpret the data.
In summary, this script can be used by a technical analyst to pinpoint potential trading opportunities, validate signals from other indicators, and customize the display of pivot points to suit their individual trading style and strategy. Always remember, however, that no single indicator should be used in isolation, and effective risk management strategies should always be employed.
Wyszukaj w skryptach "THE SCRIPT"
extended session - Regular Opening-Range- JayyOpening Range and some other scripts updated to plot correctly (see comments below.) There are three variations of the fibonacci expansion beyond the opening range and retracements within the opening range of the US Market session - I have not put in the script for the other markets yet.
The three scripts have different uses and strengths:
The extended session script (with the script here below) will plot the opening range whether you are using the extended session or the regular session. (that is to say whether "ext" in the lower right hand corner is highlighted or not.). While in the extended session the opening range has some plotting issues with periods like 13 minutes or any period that is not divisible into 330 mins with a round number outcome (eg 330/60 =5.5. Therefore an hour long opening range has problems in the extended session.
The pre session script is only for the premarket. You can select any opening range period you like. I have set the opening range to be the full premarket session. If you select a different session you will have to unselect "pre open to 9:30 EST for Opening Range?" in the format section. The script defaults to 15 minutes in the "period Of Pre Opening Range?". To go back to the 4 am to 9:30 pre opening range select "pre open to 9:30 EST for Opening Range?" there is no automatic 330 minute selection.
The past days offset script only works in 5 min or 15 minute period. It will show the opening range from up to 20 days past over the current days price action. Use this for the regular session only. 0 shows the current day's opening range. Use the positive integers for number of days back ie 1, 2, 3 etc not -1, -2, -3 etc. The script is preprogrammed to use the current day (0).
Scripts updated to plot correctly: One thing they all have in common is a way of they deal with a somewhat random problem that shifts the plots 4 hours in one direction or the other ie the plot started at 9:30 EST or 1:30PM EST. This issue started to occur approximately June 22, 2015 and impacts any script that tried to use "session" times to manage a plot in my scripts. The issue now seems to have been resolved during this past week.
Just in case the problem reoccurs I have added a "Switch session plot?" to each script. If the plot looks funny check or uncheck the "Switch session plot?" and see the difference. Of course if a new issue crops up it will likely require a different fix.
I have updated all of the scripts shown on this chart. If you are using a script of mine that suffers from the compiler issue then you will find an update on this chart. You can get any and all of the scripts by clicking on the small sideways wishbone on the left middle of the chart. You will see a dialogue box. Then click "make it mine". This will import all of the scripts to your computer and you can play around with them all to decide what you want and what you don't want. This is the easiest way to get all of the scripts in one fell swoop. It is also the easiest way for me to make all of the scripts available. I do not have all of the plots visible since it is too messy and one of the scripts (pre OR) is only for the regular session. To view the scripts click on the blue eye to the right of the script title to show it on this script. If you can only use the regular session. The scripts will all (with the exception of the pre OR) work fine.
If for any reason this script seems flakey refresh the page r try a slightly different period. I have noticed that sometimes randomly the script loves to return to the 5 min OR. This is a very new issue transient issue. As always if you see an issue please let me know.
Cheers Jayy
Options Series - Dynamic Support & Resistance
🌟 Key Features & How It Works:
⭐ Dynamic Support and Resistance Management:
The script dynamically calculates and draws support and resistance lines based on pivot highs and pivot lows. Unlike static levels that remain unchanged, these lines are updated in real-time. When a support or resistance level is breached, the corresponding line is automatically deleted, keeping the chart clean and relevant. This feature ensures that the trader is always looking at valid support and resistance levels based on the current price action.
⭐ Use of Arrays for Line Management:
The script utilizes arrays to store and manage support and resistance lines (array.new_line(0)). This is a more advanced feature of Pine Script v5, allowing for efficient handling of multiple lines on the chart. By using arrays, the script can easily track and manipulate multiple lines (adding, removing, updating), ensuring that the chart remains optimized for real-time analysis.
⭐ Customizable Inputs for Flexibility:
The script includes user inputs for the pivot length and the line width, making it adaptable to different trading styles and preferences. The pivot length determines how sensitive the indicator is to price changes, while the line width allows traders to customize the visual representation of support and resistance levels. These inputs add flexibility and make the script accessible to a broad range of traders.
⭐ Efficient Breach Detection Mechanism:
The isBreached function is a key part of the script. It checks whether the current price has breached any of the existing support or resistance levels. If a breach is detected (i.e., the price crosses below a support or above a resistance), the respective line is deleted, ensuring that only active and valid lines remain on the chart. This automatic update feature reduces the need for manual intervention, helping traders stay focused on key price levels.
⭐ Visual Clarity and Chart Cleanliness:
By deleting breached lines, the script ensures that the chart does not become cluttered with outdated or irrelevant lines. This visual clarity is crucial for traders who rely on clean, simple charts for decision-making. Removing unnecessary information helps traders make faster, more confident decisions based on the current market structure.
⭐ Scalability for Multiple Timeframes:
The use of pivot points makes the script adaptable to different timeframes, from intraday scalping to longer-term swing trading. By changing the pivot length, traders can optimize the indicator for different market environments, ensuring that it can be applied across various asset classes and timeframes.
⭐ Practical for Range-bound and Breakout Trading:
This script is particularly effective for traders who focus on range-bound markets or breakout strategies. It allows them to quickly identify areas where price is likely to reverse (support/resistance) or break out (when support/resistance is breached), providing real-time insight into market dynamics.
⭐ Simplification of Price Action Analysis:
By automating the calculation of pivots and management of support/resistance levels, the script simplifies price action analysis. Traders no longer need to manually draw or monitor these levels, which is a common task in technical analysis. This provides an edge, as it reduces the time spent on chart preparation and helps focus on executing trades.
⭐ Originality:
The script "Options Series - Pivot Based Support & Resistance" is an original approach to generating support and resistance levels using pivot points. Pivot-based techniques are popular, but the script introduces an automated dynamic way of drawing support and resistance lines, tracking breaches, and deleting lines when they are no longer valid. This aspect adds a refreshing layer of interactivity and functionality that sets it apart from basic pivot point scripts. The use of arrays to store and manage multiple support and resistance lines is also a good application of Pine Script’s newer array functionalities.
⭐ Uniqueness of the Script:
The script stands out due to its dynamic management of support and resistance lines. Unlike traditional scripts that simply plot static pivot points, this one evolves with the market by removing broken levels, ensuring only valid support and resistance lines are visible on the chart. This is particularly useful for traders who focus on clean charting. The use of arrays to store and manage the lines, alongside the efficient deletion of lines when breached, demonstrates a solid understanding of Pine Script v5's advanced features, such as array manipulation.
🚀 Conclusion:
This script stands out for its real-time adaptability, dynamic support/resistance management, and efficient use of Pine Script’s advanced features. It a powerful tool for both novice and advanced traders.
The script is an indicator designed to draw support and resistance levels based on pivot highs and lows, dynamically removing lines when they are breached. If a price crosses a support or resistance level, the respective line is deleted, ensuring the chart reflects the current state of support and resistance accurately.
WWV_LB zigzag pivot fix jayyThis is a zigzag version of LazyBear's WWV_LB. In order to plot the WWV_LB as a zigzag, it made sense to me to set the zigzag pivot at the true WWV_LB low or high pivot bars as opposed to the "pivot" bars plotted by the original WWV_LB script. The pivot point identified in the WWV_LB script is actually the point at which a wave reversal is confirmed as opposed to the true script pivot point. Confirmation of a wave reversal can, at times, lag the true pivot by a few bars especially as trendDetectionLength values increase above "1". The WWV_LB script calculates cumulative volume from wave reversal confirmation bar to wave reversal confirmation bar as opposed to the actual/true WWV_LB reversal pivot bar to reversal pivot bar. As such the waves plotted by the original and this pivot fixed scripts not only look slightly different but can also have different cumulative volumes. Confirmation of a wave reversal can lag a few bars behind the true pivot point.
The following critical lines of the original WWV_LB script determine when a wave reverses, both the true pivot and the confirmation point:mov = close>close ? 1 : close<close ? -1 : 0
trend= (mov != 0) and (mov != mov ) ? mov : nz(trend )
isTrending = rising(close, trendDetectionLength) or falling(close, trendDetectionLength)
wave=(trend != nz(wave )) and isTrending ? trend : nz(wave ) These original script lines are replicated in lines 62 to 65 of my script and are used to define wave reversal pivot bars and wave reversal confirmation bars. The original WWV_LB script does not track potential or actual pivot bars. The information can be extracted and tracked from the original script and then used to plot the actual reversal pivot bars. This allows the volume to be tracked from the actual/true pivot bars.Instead of "trendDetectionLength" I have inserted "Trend Detection Length" in the dialogue boxes. You can of course change the descriptor to what you wish by editing script line 33 to the original term or whatever you wish. You might also wish to set the default to the value "2" as per the original script. I have set the default to "3".
If you use a dark background I suggest you edit script line 4 from blackr=black to something such as blackr=yellow The volume values are shown in a vertical column of 3 numbers. Given the limitations of Pinescript Version 3 relative to V4, they are plotted at the point where the wave reversal is confirmed as opposed to the true pivot point. The zigzag lines plot the true pivot points. The plot location of numbers could be improved in Pinescript Version 4. I explain below why I have not published the Pinescript version 4 scripThe volume values plotted on the chart are calculated to be relative numbers. The script is limited to showing only three numbers vertically. Only the highest three values of a number are shown. For example, if the highest recent pip value is 12,345 only the first 3 numerals would be displayed ie 123. But suppose there is a recent value of 691. It would not be helpful to display 691 if the other wave size is shown as 123. To give the appropriate relative value the script will show a value of 7 instead of 691. This informs you of the relative magnitude of the values. This is done automatically within the script. There is likely no need to manually override the automatically calculated value. I will create a video that demonstrates the manual override method.
Should you update to Pinescript version 4? You could but if you do you will need to change the "plotchar" criteria since this script will exceed the 64 plot limit when converted to version 4. Version 4 would also allow the zigzags lines to be straight lines. However, the 50 label and line plot limit (Pinescript calls this resource sparing feature "garbage collection") significantly truncates the screen available information provided on screen. This algo optionally allows the plotting of zigzags as calculated by the original WWV_LB script. Toggling between the two script versions allows you to see the zigzag plot differences. I have also made some modifications to the original WWV_LB histogram script to adjust the pivot points.This zigzag script should be used in conjunction with the "WWV_LB pivot fix histogram jayy" shown in the panel below the main screen.
Here is a link to the original LazyBear histogram script which can be used for comparison. The differences are subtle, however, the histograms will regularly be different by a bar or two:
The lowest panel has the original LazyBear WWV_LB script for comparison. All three scripts have been set to a Trend Detection Length of 3.
jayy
Counting Stars Overlay [Market Overview Series]Hi fellow tradeurs,
So it's always been my goal to provide one of my best scripts. This is from what I call my "Market Overview" series. It is a scanner for my second best script to date. Market Overview bc of its origins as a scanner of the Kucoin Margin Coins. I realize that there are more coins that there are more margin coins that Kucoin has but I wanted to have a solid 40 coins on each coin "set". If you are unfamiliar with what I mean by 'sets' then you can view my other scanner scripts on this account for futher elaboration but to sum it up....there are 4 sets of coins I have to choose from in the settings. Each set has 40 coins in them (as there is a cap of 40 security calls that can be made per each iteration of the script on the chart). That being said...if you have the capabilities then add this script 4 times to your chart and select a diff set for each copy of the script. This has the scanner in a way that I've yet to present in my others scripts. When the alert for a coin goes off then the coins name will be printed as a label over the main chart. BTW, this was built for the 1 min timeframe and have used it EXTENSIVELY and this is the best TF for how the settings are set. I will also publish another script that will be a visual aid for this one but will rather show all the plots associated with the code that is in this scanner. Know that for the scanner it'll be best to choose a coin that has at least 1 trade/update/printed candle per minute (to be safe use BTC or ETH chart or else some of the signals will be printed if the signal arrives at a point in time where the coin on the screen does not print a candle bc no new trade or update to trades occur in TradingView. For the visual aid script that I will add right after this, there will be 20 different plots that appear. When the AVG of all of these plots is beyond the OverBought line and then the AVG line is falling for 2 bars...THEN the long signal for that coin is generated (and vise versa for short signals) Lastly regarding the visual aid script, THAT ONE will ONLY show the 20 plots that are associated with the coin that the chart is selected for. So that one is not a scanner and is just a stand alone script (again) to show whats going on in the background of this scanner. Now, once you add it however many time you want to see however many sets of coins you want, I recommend merging the scales so that they are all on one scale. I prefer mine being on the left side but all you have to do is select the 3 dots in the scripts settings in the chart window and select the scale location line and it'll open another set of lines at which point you can select "merge to scale Z" (that will be the left scale) and will put all the scales together on the left. I forgot ****If you want to see a whole diff exchange's coins you much make changes to this original script and it is further described how to do so in one of my first publications**** I REALLY hope it becomes of some benefit to you in your trading as it abundantly has in my own. It is after all one of the best of my best. Ohh, I forgot to add alerts to this but will do so immediately following this. To finish, this script DOES NOT REPAINT as far as I have EVER seen (and I have extensively searched for it bc of how good the signals were, I figured I MUST HAVE made a mistake and it did so...but alas...it does not. If you notice something on the contrary do notify me immediately with the coin, exchange, TF, and time of the occurrence and we can go from there. If anyone has any great ideas for the script then please do also let me know and if I find anyone with some abilities that mingle well with my own then lets talk as I'm always looking for good ol chaps to help me out with other scripts bc if you think this is good....well....you must imagine that I've got better that I have not/am not publishing. Aaaaaanywho, goodluck to you all. I wish you the best. ***I've got good info on how to look out for false signals but I want to see what yall come up with first before I give away all my alpha.
AND if anyone asks questions that Ive already touched on in this description or already in the comments sections then maybe someone there would be willing to waste their time answering them bc I've done quite a bit of work here that I am HAPPY to hand over to the general public but if you are not willing to do the work in reading to possibly answer your inquiries that have already been answered then I am not willing to do that work for you again. Peace and love people...peace and love. Im out.
[blackcat] L2 Ehlers Early Onset TrendLevel: 2
Background
John F. Ehlers introuced Early Onset Trend Indicator in Aug, 2014.
Function
In “The Quotient Transform” in Aug, 2014, John Ehlers described an early trend detection method, the idea of the quotient transform, that was designed to reduce the lag often found in other trend indicators. I provided a script with pine v4 code here for the early-onset trend-detection indicator and also describes an approach for creating a strategy based on this indicator as an example.
The entry points displayed in blue on the price chart are defined by the top Onset Trend Detector upper quotient crossing above a threshold value e.g zero or 0.25/-0.25 here in this script. In the article, Ehlers suggested using a different K value for the exit, so the exit points are determined by the lower Onset Trend Detector quotient crossing below a threshold e.g. zero or -0.25/0.25 here in this script.
Key Signal
Quotient1 --> upper quotient in yellow which determines long entry
Quotient2 --> lower quotient in fuchsia which determines short entry
long ---> long entry signal
short ---> short entry signal
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 82th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Realtime 5D Profile [LucF]█ OVERVIEW
This indicator displays a realtime profile that can be configured to visualize five dimensions: volume, price, time, activity and age. For each price level in a bar or timeframe, you can display total or delta volume or ticks. The tick count measures activity on a level. The thickness of each level's line indicates its age, which helps you identify the most recent levels.
█ WARNING
The indicator only works in real time. Contrary to TradingView's line of volume profile indicators , it does not show anything on historical bars or closed markets, and it cannot display volume information if none exists for the data feed the chart is using. A realtime indicator such as this one only displays information accumulated while it is running on a chart. The information it calculates cannot be saved on charts, nor can it be recalculated from historical bars. If you refresh the chart, or the script must re-execute for some reason, as when you change inputs, the accumulated information will be lost.
Because "Realtime 5D Profile" requires time to accumulate information on the chart, it will be most useful to traders working on small timeframes who trade only one instrument and do not frequently change their chart's symbol or timeframe. Traders working on higher timeframes or constantly changing charts will be better served by TradingView's volume profiles. Before using this indicator, please see the "Limitations" section further down for other important information.
█ HOW TO USE IT
Load the indicator on an active chart (see here if you don't know how).
The default configuration displays:
• A double-sided volume profile showing at what price levels activity has occurred.
• The left side shows "down" volume, the right side shows "up" volume.
• The value corresponding to each level is displayed.
• The width of lines reflects their relative value.
• The thickness of lines reflects their age. Four thicknesses are used, with the thicker lines being the most recent.
• The total value of down/up values for the profile appears at the top.
To understand how to use profiles in your trading, please research the subject. Searches on "volume profile" or "market profile" will yield many useful results. I provide you with tools — I do not teach trading. To understand more about this indicator, read on. If you choose not to do so, please don't ask me to answer questions that are already answered here, nor to make videos; I don't.
█ CONCEPTS
Delta calculations
Volume is slotted in up or down slots depending on whether the price of each new chart update is higher or lower than the previous update's price. When price does not move between chart updates, the last known direction is used. In a perfect world, Pine scripts would have access to bid and ask levels, as this would allow us to know for sure if market orders are being filled on upticks (at the ask) or downticks (at the bid). Comparing the price of successive chart updates provides the most precise way to calculate volume delta on TradingView, but it is still a compromise. Order books are in constant movement; in some cases, order cancellations can cause sudden movements of both the bid and ask levels such that the next chart update can occur on an uptick at a lower price than the previous one (or vice versa). While this update's volume should be slotted in the up slot because a buy market order was filled, it will erroneously be slotted in the down slot because the price of the chart's update is lower than that of the previous one. Luckily, these conditions are relatively rare, so they should not adversely affect calculations.
Levels
A profile is a tool that displays information organized by price levels. You can select the maximum quantity of levels this indicator displays by using the script's "Levels" input. If the profile's height is small enough for level increments to be less than the symbol's tick size, a smaller quantity of levels is used until the profile's height grows sufficiently to allow your specified quantity of levels to be displayed. The exact position of levels is not tethered to the symbol's tick increments. Activity for one level is that which happens on either side of the level, halfway between its higher or lower levels. The lowest/highest levels in the profile thus appear higher/lower than the profile's low/high limits, which are determined by the lowest/highest points reached by price during the profile's life.
Level Values and Length
The profile's vertical structure is dynamic. As the profile's height changes with the price range, it is rebalanced and the price points of its levels may be recalculated. When this happens, past updates will be redistributed among the new profile's levels, and the level values may thus change. The new levels where updates are slotted will of course always be near past ones, but keep this fluidity in mind when watching level values evolve.
The profile's horizontal structure is also dynamic. The maximum length of level lines is controlled by the "Maximum line length" input value. This maximum length is always used for the largest level value in the profile, and the length of other levels is determined by their value relative to that maximum.
Updates vs Ticks
Strictly speaking, a tick is the record of a transaction between two parties. On TradingView, these are detected on seconds charts. On other charts, ticks are aggregated to form a chart update . I use the broader "update" term when it names both events. Note that, confusingly, tick is also used to name an instrument's minimal price increment.
Volume Quality
If you use volume, it's important to understand its nature and quality, as it varies with sectors and instruments. My Volume X-ray indicator is one way you can appraise the quality of an instrument's intraday volume.
█ FEATURES
Double-Sided Profiles
When you choose one of the first two configuration selections in the "Configuration" field's dropdown menu, you are asking the indicator to display a double-sided profile, i.e., where the down values appear on the left and the up ones on the right. In this mode, the formatting options in the top section of inputs apply to both sides of the profile.
Single-Sided Profiles
The six other selections down the "Configuration" field's dropdown menu select single-sided profiles, where one side aggregates the up/down values for either volume or ticks. In this mode, the formatting options in the top section of inputs apply to the left profile. The ones in the following "Right format" section apply to the right profile.
Calculation Mode
The "Calculation" input field allows the selection of one of two modes which applies to single-sided profiles only. Values can represent the simple total of volume or ticks at each level, or their delta. The mode has no effect when a double-sided profile is used because then, the total is represented by the sum of the left and right sides. Note that when totals are selected, all levels appear in the up color.
Age
The age of each level is always displayed as one of four line thicknesses. Thicker lines are used for the youngest levels. The age of levels is determined by averaging the times of the updates composing that level. When viewing double-sided profiles, the age of each side is calculated independently, which entails you can have a down level on the left side of the profile appear thinner than its corresponding up side level line on the right side because the updates composing the up side are more recent. When calculating the age of single-sided profiles, the age of the up/down values aggregated to calculate the side are averaged. Since they may be different, the averaged level ages will not be as responsive as when using a double-sided profile configuration, where the age of levels on each side is calculated independently and follows price action more closely. Moreover, when displaying two single-sided profiles (volume on one side and ticks on the other), the age of both sides will match because they are calculated from the same realtime updates.
Profile Resets
The profile can reset on timeframes or trend changes. The usual timeframe selections are available, including the chart's, in which case the profile will reset on each new chart bar. One of two trend detection logics can be used: Supertrend or the one used by LazyBear in his Weis Wave indicator . Settings for the trend logics are in the bottommost section of the inputs, where you can also control the display of trend changes and states. Note that the "Timeframe" field's setting also applies to the trend detection mechanism. Whatever the timeframe used for trend detection, its logic will not repaint.
Format
Formatting a profile for charts is often a challenge for traders, and this one is no exception. Varying zoom factors on your chart and the frequency of profile resets will require different profile formats. You can achieve a reasonable variety of effects by playing with the following input fields:
• "Resets on" controls how frequently new profiles are drawn. Spacing out profiles between bars can help make them more usable.
• "Levels" determines the maximum quantity of levels displayed.
• "Offset" allows you to shift the profile horizontally.
• "Profile size" affects the global size of the profile.
• Another "Size" field provides control over the size of the totals displayed above the profile.
• "Maximum line length" controls how far away from the center of the bar the lines will stretch left and right.
Colors
The color and brightness of levels and totals always allows you to determine the winning side between up and down values. On double-sided profiles, each side is always of one color, since the left side is down values and the right side, up values. However, the losing side is colored with half its brightness, so the emphasis is put on the winning side. When there is no winner, the toned-down version of each color is used for both sides. Single-sided profiles use the up and down colors in full brightness on the same side. Which one is used reflects the winning side.
Candles
The indicator can color candle bodies and borders independently. If you choose to do so, you may want to disable the chart's bars by using the eye icon near the symbol's name.
Tooltips
A tooltip showing the value of each level is available. If they do not appear when hovering over levels, select the indicator by clicking on its chart name. This should get the tooltips working.
Data Window
As usual, I provide key values in the Data Window, so you can track them. If you compare total realtime volumes for the profile and the built-in "Volume" indicator, you may see variations at some points. They are due to the different mechanisms running each program. In my experience, the values from the built-in don't always update as often as those of the profile, but they eventually catch up.
█ LIMITATIONS
• The levels do not appear exactly at the position they are calculated. They are positioned slightly lower than their actual price levels.
• Drawing a 20-level double-sided profile with totals requires 42 labels. The script will only display the last 500 labels,
so the number of levels you choose affects how many past profiles will remain visible.
• The script is quite taxing, which will sometimes make the chart's tab less responsive.
• When you first load the indicator on a chart, it will begin calculating from that moment; it will not take into account prior chart activity.
• If you let the script run long enough when using profile reset criteria that make profiles last for a long time, the script will eventually run out of memory,
as it will be tracking unmanageable amounts of chart updates. I don't know the exact quantity of updates that will cause this,
but the script can handle upwards of 60K updates per profile, which should last 1D except on the most active markets. You can follow the number of updates in the Data Window.
• The indicator's nature makes it more useful at very small timeframes, typically in the sub 15min realm.
• The Weis Wave trend detection used here has nothing to do with how David Weis detects trend changes.
LazyBear's version was a port of a port, so we are a few generations removed from the Weis technique, which uses reversals by a price unit.
I believe the version used here is useful nonetheless because it complements Supertrend rather well.
█ NOTES
The aggregated view that volume and tick profiles calculate for traders is a good example of one of the most useful things software can do for traders: look at things from a methodical, mathematical perspective, and present results in a meaningful way. Profiles are powerful because, if the volume data they use is of good enough quality, they tell us what levels are important for traders, regardless of the nature or rationality of the methods traders have used to determine those levels. Profiles don't care whether traders use the news, fundamentals, Fib numbers, pivots, or the phases of the moon to find "their" levels. They don't attempt to forecast or explain markets. They show us real stuff containing zero uncertainty, i.e., what HAS happened. I like this.
The indicator's "VPAA" chart name represents four of the five dimensions the indicator displays: volume, price, activity and age. The time dimension is implied by the fact it's a profile — and I couldn't find a proper place for a "T" in there )
I have not included alerts in the script. I may do so in the future.
For the moment, I have no plans to write a profile indicator that works on historical bars. TradingView's volume profiles already do that, and they run much faster than Pine versions could, so I don't see the point in spending efforts on a poor ersatz.
For Pine Coders
• The script uses labels that draw varying quantities of characters to break the limitation constraining other Pine plots/lines to bar boundaries.
• The code's structure was optimized for performance. When it was feasible, global arrays, "input" and other variables were used from functions,
sacrificing function readability and portability for speed. Code was also repeated in some places, to avoid the overhead of frequent function calls in high-traffic areas.
• I wrote my script using the revised recommendations in the Style Guide from the Pine v5 User Manual.
█ THANKS
• To Duyck for his function that sorts an array while keeping it in synch with another array.
The `sortTwoArrays()` function in my script is derived from the Pine Wizard 's code.
• To the one and only Maestro, RicardoSantos , the creative volcano who worked hard to write a function to produce fixed-width, figure space-padded numeric values.
A change in design made the function unnecessary in this script, but I am grateful to you nonetheless.
• To midtownskr8guy , another Pine Wizard who is also a wizard with colors. I use the colors from his Pine Color Magic and Chart Theme Simulator constantly.
• Finally, thanks to users of my earlier "Delta Volume" scripts. Comments and discussions with them encouraged me to persist in figuring out how to achieve what this indicator does.
PSv4.0 Limited Array Support Super HackThis is my "PSv4.0 Limited Array Support Super Hack", derived from MichelT's Workaround for Arrays in pine and Bubble sort script, except this utilizes line.new() to obtain one array with up to 100 indices. I provided functions that may be syntactically comparable in operation to the array class we should get with PSv5.0 when that arrives. I have no clue when that ETA shall be either, so your guess is as good as mine. Due to the complexity of the script, I would ONLY recommend this script's functions for reuse by advanced Pine programmers, not newcomers to Pine Script.
Notice: FYI, support for these functions will be limited to only errata with the included functions. Honestly, I don't have an abundance of time on a daily basis to assist members with incorporation into their newly developed scripts. I hope you will understand.
The intention of this script is to provide Pine developers with one large array having up to 100 indices until we have full native array support in the future. Availability of full use of the array is only obtained when bar_index is indicesCount-1, so bear that in mind. This script is so computationally expensive, I would only advise using it "as is" on 5Y and All Charts at it's current initial release. On smaller sampling rates such as 1D, 5D and 1M... it has a tendency to encounter runtime errors such as this message: "Calculation timed out. Remove the indicator and reapply it to the chart". I just switch to a larger sampling interval - 5Y or All. I believe this is occurring due mostly to prng() generating thousands of random floating point numbers, PLUS the overhead of using line.new() for something it wasn't originally intended for. It does also use 64 plots in full color, maxing out the plotting capabilities of Pine as well. With usage of the array functions alone in your code, I anticipate those scripts to be more server friendly.
Basically this scripts functionality, as is, generates 32 pseudorandom numbers per bar in a sky blue birds nest of random numbers. It then sorts them numerically and plots them once again in a visually stunning rainbow spectrum. You will notice the plot()s colors will invert when the sorting order is changed in Settings. I commented out a lot of plot()s because we are limited to a maximum of 64 plot()s. By commenting and uncommenting with highlighted text blocks and + , you may alter the scripts appearance when done properly.
Overall, I hope you find it useful with incorporating expected array functionality that will perpetuate the novel development of next generation indicators in Pine Script version 4.0 . Once again, check out MichelT's brilliantly crafted script mentioned above. You may be able to use both scripts incorporated into an all-in-one to have dual array support, BUT I have not tested this yet, be forewarned. I hope the community contribution of this script in open source is of some benefit to those who can utilize it properly. As always, I have included advanced Pine programming techniques that conform to proper "Pine Etiquette", so this script is more than just a complex array provision...
The comments section below is solely just for commenting and other remarks, ideas, compliments, etc... regarding only this indicator, not others. When available time provides itself, I will consider your inquiries, thoughts, and concepts presented below in the comments section, should you have any questions or comments regarding this indicator. When my indicators achieve more prevalent use by TV members, I may implement more ideas when they present themselves as worthy additions. As always, "Like" it if you simply just like it with a proper thumbs up, and also return to my scripts list occasionally for additional postings. Have a profitable future everyone!
[blackcat] L2 Ehlers Empirical Mode TraderCircumstance Remarks: Because of my carelessness, the script of the same name that I posted before was banned and hidden because the description contained content that violated the TradingView House Rule. After communicating with the MOD, I corrected the description and obtained permission to publish it again. I hereby declare. Sorry for the inconvenience!
Level: 2
Background
John F. Ehlers introuced Empirical Mode Trader Indicator in Mar, 2010.
Function
In his article “Empirical Mode Decomposition,” John Ehlers and Ric Way suggest using methods based on bandpass filtering to distinguish trending from cycling markets. The article’s trading suggestions were used to create the Empirical Mode strategy given here for pine v4 script. If the strategy determines that the marke is in trending mode, then the strategy is allowed to trade with the trend — either long, in uptrends, or short, in downtrends. If the indicator determines that the market is in cycling mode, then the strategy allows trading cycle extremes, using Bollinger bands to trigger entries. You can do this by Choosing either cycle or trend mode at inputs.
Key Signal
Trend ---> Trend signal
FracAvgPeak ---> Upper band signal
FracAvgValley ---> Lower band signal
Pros and Cons
100% John F. Ehlers definition translation, even variable names are the same. This help readers who would like to use pine to read his book.
Remarks
The 75th script for Blackcat1402 John F. Ehlers Week publication.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
[blackcat] L2 Ehlers Sine Wave Coupled Eight Planetary CycleLevel: 2
Background
Have you considered that factors outside the Earth will be related to macro market trends? Let’s discuss the relationship between the planetary movement in the Galaxy and the market movement on Earth today! Although I said that, you may have laughed out in front of the screen, but the calculations in this script are entirely based on astronomical data and mathematical relationships.
Your next question may be why you compare the movements of the eight planets and the laws of the market on the earth together? My answer comes from a Cybernetic Sine Wave indicator proposed by Dr. John F. Ehlers.
Function
L2 Ehlers Sine Wave Coupled Eight Planetary Cycle first converts the astronomical data of the eight major planets into planetary aspects/phases through mathematical relationships. Planetary aspects/phases can provide the historical and current relative positions of each planet in the mathematical triangle relationship. We can use a simple mathematical sine formula to constrain the planet's trajectory between -1 and 1, which is what we often call a sine wave.
The relationship between the sine wave and the market can be extracted from the theory of John F. Ehlers. In Ehlers' theory, market price can be modeled by the trend and cycle modes. And in his works, there are many indicators of how to completely remove the trend in the market price and only leave the cycle mode data. The Cybernetic Sine Wave indicator is exactly the cycle mode data after the market trend is stripped, and expressed in the form of a sine wave.
If you can read to here with patience, you must also be aware of the premise that the trajectories of the eight planets and the laws of the earth market can be coupled: the trajectory of the sine wave mode. Therefore, this indicator is a tool for comparing and analyzing the two in the same chart. I hope you like it.
Finally, in order to benchmark the trajectories of the eight planets and the specific market on the earth, a starting point in time is particularly important. This is the base date of the market index to be analyzed. It is the year, month, and day data specified by the index, which needs to be input by the user when analyzing a specific stock index. For example, the base date of the S&P 500 index is January 3, 1928. This date needs to be entered into the indicator to analyze the SPX500.
Key Signal
Mercury_trail ---> smoothed Mercury orbit sine wave
Venus_trail ---> smoothed Venus orbit sine wave
Earth_trail ---> smoothed Earth orbit sine wave
Earth_mirror ---> smoothed Earth mirrored orbit sine wave
Mars_trail ---> smoothed Mars orbit sine wave
Jupiter_trail ---> smoothed Jupiter orbit sine wave
Saturn_trail ---> smoothed Saturn orbit sine wave
Uranus_trail ---> smoothed Uranus orbit sine wave
Neptune_trail ---> smoothed Neptune orbit sine wave
Aspect 0, 45, 90, 225, 270 deg ---> key planet aspects
ehlersine ---> Ehlers Cybernetic Sine Wave
ehlerslsine ---> Ehlers Cybernetic Lead Sine Wave
Pros and Cons
This is a technical indicator that I have come up with on a whim, and the laws of planetary operation and the operation of the Earth market are still being explored. Hope that interested friends will share your new discoveries.
Remarks
To celebrate I released the 50th technical indicator script on TV!
Courtesy of @sal157011 John Ehlers "Cybernetic Sine Wave" indicator, I converted it from pine v2 to pine v4 in this script.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
L1 Moving Average Fingerprint for Long EntryLevel: 1
Background
This script combines moving average processing with highest high and lowest low to disclose the "fingerprint" of a specific trading pair to describe its unique behavior.
Function
Moving Average Fingerprint for Long Entry is a Level 1 pine script. It utilize several moving average of inherent highest high and lowest low and combine them with customized fingerprint coefficients to depict the unique behavior of a specific trading pair across multiple markets for long entry point identification.
Key Signal
FingerPrint1~6 are basic-level fingerprints with moving average of highest high and lowest low.
FingerPrint7~8 are composite fingerprint definitions with coefficients/weights,where coefficients/weights need to be tuned to discover the inherent "fingerprint" of a specific trading pair.
FingerPrint10~12 are composite fingerprint calculation for long entry alerts
ReadytoLong is a long entry filter where long entry point may happen within it. By using crossover() function to a customized threshold value, you can define accurate long entries.
Pros and Cons
Pros:
1. Combine moving average and extreme points to disclose a trading pair behavior.
2. Smart to tune specific set of parameters to obtain unique fingerprints of trading pairs.
3. Smart position sizing scheme by adjusting the threshold values.
Cons:
1. Require tune input parameters for each trading pair in a specific period and time frame.
2. Only long entry was studied, no short entry and re-entry are available yet to form as a trading system.
3. "ReadytoLong" is an inaccurate range where multiple long entries may happen at improper points in chop market.
4. Complex input parameters to obtain a unique fingerprint set.
Remarks
Although I wrote pine script for more than two years, this is the first script published in the community. I will publish more with my works in this platform.
Hope the community can improve this concept and make it as a trading system.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Using `varip` variables [PineCoders]█ OVERVIEW
The new varip keyword in Pine can be used to declare variables that escape the rollback process, which is explained in the Pine User Manual's page on the execution model . This publication explains how Pine coders can use variables declared with varip to implement logic that was impossible to code in Pine before, such as timing events during the realtime bar, or keeping track of sequences of events that occur during successive realtime updates. We present code that allows you to calculate for how much time a given condition is true during a realtime bar, and show how this can be used to generate alerts.
█ WARNINGS
1. varip is an advanced feature which should only be used by coders already familiar with Pine's execution model and bar states .
2. Because varip only affects the behavior of your code in the realtime bar, it follows that backtest results on strategies built using logic based on varip will be meaningless,
as varip behavior cannot be simulated on historical bars. This also entails that plots on historical bars will not be able to reproduce the script's behavior in realtime.
3. Authors publishing scripts that behave differently in realtime and on historical bars should imperatively explain this to traders.
█ CONCEPTS
Escaping the rollback process
Whereas scripts only execute once at the close of historical bars, when a script is running in realtime, it executes every time the chart's feed detects a price or volume update. At every realtime update, Pine's runtime normally resets the values of a script's variables to their last committed value, i.e., the value they held when the previous bar closed. This is generally handy, as each realtime script execution starts from a known state, which simplifies script logic.
Sometimes, however, script logic requires code to be able to save states between different executions in the realtime bar. Declaring variables with varip now makes that possible. The "ip" in varip stands for "intrabar persist".
Let's look at the following code, which does not use varip :
//@version=4
study("")
int updateNo = na
if barstate.isnew
updateNo := 1
else
updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
On historical bars, barstate.isnew is always true, so the plot shows a value of "1". On realtime bars, barstate.isnew is only true when the script first executes on the bar's opening. The plot will then briefly display "1" until subsequent executions occur. On the next executions during the realtime bar, the second branch of the if statement is executed because barstate.isnew is no longer true. Since `updateNo` is initialized to `na` at each execution, the `updateNo + 1` expression yields `na`, so nothing is plotted on further realtime executions of the script.
If we now use varip to declare the `updateNo` variable, the script behaves very differently:
//@version=4
study("")
varip int updateNo = na
if barstate.isnew
updateNo := 1
else
updateNo := updateNo + 1
plot(updateNo, style = plot.style_circles)
The difference now is that `updateNo` tracks the number of realtime updates that occur on each realtime bar. This can happen because the varip declaration allows the value of `updateNo` to be preserved between realtime updates; it is no longer rolled back at each realtime execution of the script. The test on barstate.isnew allows us to reset the update count when a new realtime bar comes in.
█ OUR SCRIPT
Let's move on to our script. It has three parts:
— Part 1 demonstrates how to generate alerts on timed conditions.
— Part 2 calculates the average of realtime update prices using a varip array.
— Part 3 presents a function to calculate the up/down/neutral volume by looking at price and volume variations between realtime bar updates.
Something we could not do in Pine before varip was to time the duration for which a condition is continuously true in the realtime bar. This was not possible because we could not save the beginning time of the first occurrence of the true condition.
One use case for this is a strategy where the system modeler wants to exit before the end of the realtime bar, but only if the exit condition occurs for a specific amount of time. One can thus design a strategy running on a 1H timeframe but able to exit if the exit condition persists for 15 minutes, for example. REMINDER: Using such logic in strategies will make backtesting their complete logic impossible, and backtest results useless, as historical behavior will not match the strategy's behavior in realtime, just as using `calc_on_every_tick = true` will do. Using `calc_on_every_tick = true` is necessary, by the way, when using varip in a strategy, as you want the strategy to run like a study in realtime, i.e., executing on each price or volume update.
Our script presents an `f_secondsSince(_cond, _resetCond)` function to calculate the time for which a condition is continuously true during, or even across multiple realtime bars. It only works in realtime. The abundant comments in the script hopefully provide enough information to understand the details of what it's doing. If you have questions, feel free to ask in the Comments section.
Features
The script's inputs allow you to:
• Specify the number of seconds the tested conditions must last before an alert is triggered (the default is 20 seconds).
• Determine if you want the duration to reset on new realtime bars.
• Require the direction of alerts (up or down) to alternate, which minimizes the number of alerts the script generates.
The inputs showcase the new `tooltip` parameter, which allows additional information to be displayed for each input by hovering over the "i" icon next to it.
The script only displays useful information on realtime bars. This information includes:
• The MA against which the current price is compared to determine the bull or bear conditions.
• A dash which prints on the chart when the bull or bear condition is true.
• An up or down triangle that prints when an alert is generated. The triangle will only appear on the update where the alert is triggered,
and unless that happens to be on the last execution of the realtime bar, it will not persist on the chart.
• The log of all triggered alerts to the right of the realtime bar.
• A gray square on top of the elapsed realtime bars where one or more alerts were generated. The square's tooltip displays the alert log for that bar.
• A yellow dot corresponding to the average price of all realtime bar updates, which is calculated using a varip array in "Part 2" of the script.
• Various key values in the Data Window for each parts of the script.
Note that the directional volume information calculated in Part 3 of the script is not plotted on the chart—only in the Data Window.
Using the script
You can try running the script on an open market with a 30sec timeframe. Because the default settings reset the duration on new realtime bars and require a 20 second delay, a reasonable amount of alerts will trigger.
Creating an alert on the script
You can create a script alert on the script. Keep in mind that when you create an alert from this script, the duration calculated by the instance of the script running the alert will not necessarily match that of the instance running on your chart, as both started their calculations at different times. Note that we use alert.freq_all in our alert() calls, so that alerts will trigger on all instances where the associated condition is met. If your alert is being paused because it reaches the maximum of 15 triggers in 3 minutes, you can configure the script's inputs so that up/down alerts must alternate. Also keep in mind that alerts run a distinct instance of your script on different servers, so discrepancies between the behavior of scripts running on charts and alerts can occur, especially if they trigger very often.
Challenges
Events detected in realtime using variables declared with varip can be transient and not leave visible traces at the close of the realtime bar, as is the case with our script, which can trigger multiple alerts during the same realtime bar, when the script's inputs allow for this. In such cases, elapsed realtime bars will be of no use in detecting past realtime bar events unless dedicated code is used to save traces of events, as we do with our alert log in this script, which we display as a tooltip on elapsed realtime bars.
█ NOTES
Realtime updates
We have no control over when realtime updates occur. A realtime bar can open, and then no realtime updates can occur until the open of the next realtime bar. The time between updates can vary considerably.
Past values
There is no mechanism to refer to past values of a varip variable across realtime executions in the same bar. Using the history-referencing operator will, as usual, return the variable's committed value on previous bars. If you want to preserve past values of a varip variable, they must be saved in other variables or in an array .
Resetting variables
Because varip variables not only preserve their values across realtime updates, but also across bars, you will typically need to plan conditions that will at some point reset their values to a known state. Testing on barstate.isnew , as we do, is a good way to achieve that.
Repainting
The fact that a script uses varip does not make it necessarily repainting. A script could conceivably use varip to calculate values saved when the realtime bar closes, and then use confirmed values of those calculations from the previous bar to trigger alerts or display plots, avoiding repaint.
timenow resolution
Although the variable is expressed in milliseconds it has an actual resolution of seconds, so it only increments in multiples of 1000 milliseconds.
Warn script users
When using varip to implement logic that cannot be replicated on historical bars, it's really important to explain this to traders in published script descriptions, even if you publish open-source. Remember that most TradingViewers do not know Pine.
New Pine features used in this script
This script uses three new Pine features:
• varip
• The `tooltip` parameter in input() .
• The new += assignment operator. See these also: -= , *= , /= and %= .
Example scripts
These are other scripts by PineCoders that use varip :
• Tick Delta Volume , by RicadoSantos .
• Tick Chart and Volume Info from Lower Time Frames by LonesomeTheBlue .
Thanks
Thanks to the PineCoders who helped improve this publication—especially to bmistiaen .
Look first. Then leap.
[blackcat] L2 Price Envelope TrackerLevel: 2
Background
Price envelopes sare shown at a set percentage above and below a moving average. They are used to indicate overbought and oversold levels and can be traded individually or in conjunction with a momentum indicator.
Function
L2 Price Envelope Tracker is an innovative indicator that use customized envelope of price to disclose overbought and oversold periods. With this function, long and short entries can be further developped in this pine script.
Key Signal
sma5 --> typical price moving average line
resistance --> upper envelope as resistance line
support ---> lower envelope as support line
Pros and Cons
Pros:
1. easy observe overbought and oversold zone
2. disclose exact long and short entries in overbought and oversold zones
Cons:
1. Only applicable for the trading pairs that support financial() functions. crypto/xau/xag/indice are not applicable
2. Need to tune r1 and s1 for different trading pairs
Remarks
NA
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
CRT Hourly/15m dividers and opensRange Separator is a unique tool designed to help traders visualize critical price levels and ranges on their charts. This script employs the innovative concepts of "Candles Are Ranges" and the "Power of 3 (PO3)" to enhance trading strategies by marking key time intervals and price levels.
What the Script Does:
Hourly Lines:
Automatically draws vertical lines at the start of each hour.
Provides an option to display only the current hour's line for a cleaner visual.
Allows customization of line color, width, and style.
15-Minute Lines:
Adds vertical lines at 15-minute intervals to highlight smaller time ranges.
Includes an option to draw horizontal lines at the 15-minute interval prices.
Offers customization for line color, width, and style.
Horizontal Lines:
Draws horizontal lines based on the opening, high, or low price of the selected timeframe.
Customizable options for line color, width, and style.
How the Script Works:
Candles Are Ranges: Each candle represents a price range (OHLC) on any timeframe. The script visually emphasizes these ranges, helping traders understand price action better.
Power of 3 (PO3): This concept divides price delivery into three stages: formation, turtle soup (stop hunting), and distribution/expansion. The script marks these intervals, aiding in identifying potential key levels for entries and exits.
How to Use the Script:
Adding the Script:
Apply the script to your chart and adjust the settings in the input menu.
Customize the appearance of hourly and 15-minute lines to suit your preference.
Analyzing the Chart:
Observe the hourly lines to determine higher timeframe biases.
Use 15-minute lines to identify more granular price movements.
Pay attention to horizontal lines that mark significant price levels based on your chosen criteria (open, high, low).
Trading Strategy:
Combine the script's visual aids with your understanding of the "Candles Are Ranges" and "Power of 3" concepts.
Use these visual cues to make informed decisions about potential entry and exit points.
What Makes it Original:
Integration of Candles Are Ranges and PO3 Concepts: Unlike traditional scripts that merely plot lines, this script uniquely integrates two powerful trading theories to provide a comprehensive view of price action.
Customizable Visual Aids: Offers extensive customization options for line colors, widths, and styles, allowing traders to tailor the script to their specific needs.
Enhanced Timeframe Analysis: By marking both hourly and 15-minute intervals, the script provides a detailed view of price ranges across multiple timeframes, enhancing the trader's ability to make informed decisions.
- Key script Parameters
Show Hourly Lines: Toggles the display of vertical lines marking each hour.
Hourly Lines Color: Sets the color of the hourly vertical lines.
Hourly Lines Width: Chooses the width of the hourly vertical lines (1, 2, or 3).
Hourly Lines Style: Selects the style of the hourly lines (Solid, Dashed, or Dotted).
Horizontal Line Color: Defines the color of the horizontal lines drawn at hourly intervals.
Horizontal Line Width: Determines the width of the horizontal lines (1, 2, or 3).
Horizontal Line Style: Sets the style of the horizontal lines (Solid, Dashed, or Dotted).
Horizontal Line Start Price: Specifies which price (Open, High, Low) the horizontal lines will start from.
Show Current Hour Only: Limits the display to only the current hour's horizontal line.
Show 15-Minute Lines: Toggles the display of vertical lines marking each 15-minute interval.
15-Minute Lines Color: Sets the color of the 15-minute vertical lines.
15-Minute Lines Width: Chooses the width of the 15-minute vertical lines (1, 2, or 3).
15-Minute Lines Style: Selects the style of the 15-minute lines (Solid, Dashed, or Dotted).
Show 15-Minute Horizontal Lines: Toggles the display of horizontal lines at 15-minute intervals.
15-Minute Horizontal Lines Color: Defines the color of the horizontal lines drawn at 15-minute intervals.
15-Minute Horizontal Lines Width: Determines the width of the horizontal lines (1, 2, or 3).
15-Minute Horizontal Lines Style: Sets the style of the horizontal lines (Solid, Dashed, or Dotted).
Important Notes:
- Credit to @Yazdanian and his basic "Hourly separators" indicator that plots a simple vertical line every hour which provided the idea for this version and expanded on
- This script is designed to complement your trading strategy by providing visual aids and should be used alongside other technical analysis tools.
It is not intended to issue buy or sell signals but to help you understand price ranges and potential key levels.
Disclaimer: The script is provided as-is, and the authors are not responsible for any trading losses incurred using this script. Always perform your own analysis and use proper risk management.
VisibleChart█ OVERVIEW
This library is a Pine programmer’s tool containing functions that return values calculated from the range of visible bars on the chart.
This is now possible in Pine Script™ thanks to the recently-released chart.left_visible_bar_time and chart.right_visible_bar_time built-ins, which return the opening time of the leftmost and rightmost bars on the chart. These values update as traders scroll or zoom their charts, which gives way to a class of indicators that can dynamically recalculate and draw visuals on visible bars only, as users scroll or zoom their charts. We hope this library's functions help you make the most of the world of possibilities these new built-ins provide for Pine scripts.
For an example of a script using this library, have a look at the Chart VWAP indicator.
█ CONCEPTS
Chart properties
The new chart.left_visible_bar_time and chart.right_visible_bar_time variables return the opening time of the leftmost and rightmost bars on the chart. They are only two of many new built-ins in the `chart.*` namespace. See this blog post for more information, or look them up by typing "chart." in the Pine Script™ Reference Manual .
Dynamic recalculation of scripts on visible bars
Any script using chart.left_visible_bar_time or chart.right_visible_bar_time acquires a unique property, which triggers its recalculation when traders scroll or zoom their charts in such a way that the range of visible bars on the chart changes. This library's functions use the two recent built-ins to derive various values from the range of visible bars.
Designing your scripts for dynamic recalculation
For the library's functions to work correctly, they must be called on every bar. For reliable results, assign their results to global variables and then use the variables locally where needed — not the raw function calls.
Some functions like `barIsVisible()` or `open()` will return a value starting on the leftmost visible bar. Others such as `high()` or `low()` will also return a value starting on the leftmost visible bar, but their correct value can only be known on the rightmost visible bar, after all visible bars have been analyzed by the script.
You can plot values as the script executes on visible bars, but efficient code will, when possible, create resource-intensive labels, lines or tables only once in the global scope using var , and then use the setter functions to modify their properties on the last bar only. The example code included in this library uses this method.
Keep in mind that when your script uses chart.left_visible_bar_time or chart.right_visible_bar_time , your script will recalculate on all bars each time the user scrolls or zooms their chart. To provide script users with the best experience you should strive to keep calculations to a minimum and use efficient code so that traders are not always waiting for your script to recalculate every time they scroll or zoom their chart.
Another aspect to consider is the fact that the rightmost visible bar will not always be the last bar in the dataset. When script users scroll back in time, a large portion of the time series the script calculates on may be situated after the rightmost visible bar. We can never assume the rightmost visible bar is also the last bar of the time series. Use `barIsVisible()` to restrict calculations to visible bars, but also consider that your script can continue to execute past them.
Look first. Then leap.
█ FUNCTIONS
The library contains the following functions:
barIsVisible()
Condition to determine if a given bar is within the users visible time range.
Returns: (bool) True if the the calling bar is between the `chart.left_visible_bar_time` and the `chart.right_visible_bar_time`.
high()
Determines the value of the highest `high` in visible bars.
Returns: (float) The maximum high value of visible chart bars.
highBarIndex()
Determines the `bar_index` of the highest `high` in visible bars.
Returns: (int) The `bar_index` of the `high()`.
highBarTime()
Determines the bar time of the highest `high` in visible bars.
Returns: (int) The `time` of the `high()`.
low()
Determines the value of the lowest `low` in visible bars.
Returns: (float) The minimum low value of visible chart bars.
lowBarIndex()
Determines the `bar_index` of the lowest `low` in visible bars.
Returns: (int) The `bar_index` of the `low()`.
lowBarTime()
Determines the bar time of the lowest `low` in visible bars.
Returns: (int) The `time` of the `low()`.
open()
Determines the value of the opening price in the visible chart time range.
Returns: (float) The `open` of the leftmost visible chart bar.
close()
Determines the value of the closing price in the visible chart time range.
Returns: (float) The `close` of the rightmost visible chart bar.
leftBarIndex()
Determines the `bar_index` of the leftmost visible chart bar.
Returns: (int) A `bar_index`.
rightBarIndex()
Determines the `bar_index` of the rightmost visible chart bar.
Returns: (int) A `bar_index`
bars()
Determines the number of visible chart bars.
Returns: (int) The number of bars.
volume()
Determines the sum of volume of all visible chart bars.
Returns: (float) The cumulative sum of volume.
ohlcv()
Determines the open, high, low, close, and volume sum of the visible bar time range.
Returns: ( ) A tuple of the OHLCV values for the visible chart bars. Example: open is chart left, high is the highest visible high, etc.
chartYPct(pct)
Determines a price level as a percentage of the visible bar price range, which depends on the chart's top/bottom margins in "Settings/Appearance".
Parameters:
pct : (series float) Percentage of the visible price range (50 is 50%). Negative values are allowed.
Returns: (float) A price level equal to the `pct` of the price range between the high and low of visible chart bars. Example: 50 is halfway between the visible high and low.
chartXTimePct(pct)
Determines a time as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
chartXIndexPct(pct)
Determines a `bar_index` as a percentage of the visible bar time range.
Parameters:
pct : (series float) Percentage of the visible time range (50 is 50%). Negative values are allowed.
Returns: (float) A time in UNIX format equal to the `pct` of the time range from the `chart.left_visible_bar_time` to the `chart.right_visible_bar_time`. Example: 50 is halfway from the leftmost visible bar to the rightmost.
whenVisible(src, whenCond, length)
Creates an array containing the `length` last `src` values where `whenCond` is true for visible chart bars.
Parameters:
src : (series int/float) The source of the values to be included.
whenCond : (series bool) The condition determining which values are included. Optional. The default is `true`.
length : (simple int) The number of last values to return. Optional. The default is all values.
Returns: (float ) The array ID of the accumulated `src` values.
avg(src)
Gathers values of the source over visible chart bars and averages them.
Parameters:
src : (series int/float) The source of the values to be averaged. Optional. Default is `close`.
Returns: (float) A cumulative average of values for the visible time range.
median(src)
Calculates the median of a source over visible chart bars.
Parameters:
src : (series int/float) The source of the values. Optional. Default is `close`.
Returns: (float) The median of the `src` for the visible time range.
vVwap(src)
Calculates a volume-weighted average for visible chart bars.
Parameters:
src : (series int/float) Source used for the VWAP calculation. Optional. Default is `hlc3`.
Returns: (float) The VWAP for the visible time range.
Delta Volume Candles [LucF]█ OVERVIEW
This indicator plots on-chart volume delta information using candles that can replace your normal candles, tops and bottoms appended to normal candles, optional MAs of those tops and bottoms levels, a divergence channel and a chart background. The indicator calculates volume delta using intrabar analysis, meaning that it uses the lower timeframe bars constituting each chart bar.
█ CONCEPTS
Volume Delta
The volume delta concept divides a bar's volume in "up" and "down" volumes. The delta is calculated by subtracting down volume from up volume. Many calculation techniques exist to isolate up and down volume within a bar. The simplest use the polarity of interbar price changes to assign their volume to up or down slots, e.g., On Balance Volume or the Klinger Oscillator . Others such as Chaikin Money Flow use assumptions based on a bar's OHLC values. The most precise calculation method uses tick data and assigns the volume of each tick to the up or down slot depending on whether the transaction occurs at the bid or ask price. While this technique is ideal, it requires huge amounts of data on historical bars, which considerably limits the historical depth of charts and the number of symbols for which tick data is available. Furthermore, historical tick data is not yet available on TradingView.
This indicator uses intrabar analysis to achieve a compromise between the simplest and most precise methods of calculating volume delta. It is currently the most precise method usable on TradingView charts. TradingView's Volume Profile built-in indicators use it, as do the CVD - Cumulative Volume Delta Candles and CVD - Cumulative Volume Delta (Chart) indicators published from the TradingView account . My Delta Volume Channels and Volume Delta Columns Pro indicators also use intrabar analysis. Other volume delta indicators such as my Realtime 5D Profile use realtime chart updates to calculate volume delta without intrabar analysis, but that type of indicator only works in real time; they cannot calculate on historical bars.
This is the logic I use to determine the polarity of intrabars, which determines the up or down slot where its volume is added:
• If the intrabar's open and close values are different, their relative position is used.
• If the intrabar's open and close values are the same, the difference between the intrabar's close and the previous intrabar's close is used.
• As a last resort, when there is no movement during an intrabar, and it closes at the same price as the previous intrabar, the last known polarity is used.
Once all intrabars making up a chart bar have been analyzed and the up or down property of each intrabar's volume determined, the up volumes are added, and the down volumes subtracted. The resulting value is volume delta for that chart bar, which can be used as an estimate of the buying/selling pressure on an instrument. Not all markets have volume information. Without it, this indicator is useless.
Intrabar analysis
Intrabars are chart bars at a lower timeframe than the chart's. The timeframe used to access intrabars determines the number of intrabars accessible for each chart bar. On a 1H chart, each chart bar of an active market will, for example, usually contain 60 bars at the lower timeframe of 1min, provided there was market activity during each minute of the hour.
This indicator automatically calculates an appropriate lower timeframe using the chart's timeframe and the settings you use in the script's "Intrabars" section of the inputs. As it can access lower timeframes as small as seconds when available, the indicator can be used on charts at relatively small timeframes such as 1min, provided the market is active enough to produce bars at second timeframes.
The quantity of intrabars analyzed in each chart bar determines:
• The precision of calculations (more intrabars yield more precise results).
• The chart coverage of calculations (there is a 100K limit to the quantity of intrabars that can be analyzed on any chart,
so the more intrabars you analyze per chart bar, the less chart bars can be calculated by the indicator).
The information box displayed at the bottom right of the chart shows the lower timeframe used for intrabars, as well as the average number of intrabars detected for chart bars and statistics on chart coverage.
Balances
This indicator calculates five balances from volume delta values. The balances are oscillators with a zero centerline; positive values are bullish, and negative values are bearish. It is important to understand the balances as they can be used to:
• Color candle bodies.
• Calculate body and top and bottom divergences.
• Color an EMA channel.
• Color the chart's background.
• Configure markers and alerts.
The five balances are:
1 — Bar Balance : This is the only balance using instant values; it is simply the subtraction of the down volume from the up volume on the bar, so the instant volume delta for that bar.
2 — Average Balance : Calculates a distinct EMA for both the up and down volumes, and subtracts the down EMA from the up EMA.
The result is akin to MACD's histogram because it is the subtraction of two moving averages.
3 — Momentum Balance : Starts by calculating, separately for both up and down volumes, the difference between the same EMAs used in "Average Balance" and
an SMA of twice the period used for the "Average Balance" EMAs. The difference for the up side is subtracted from the difference for the down side,
and an RSI of that value is calculated and brought over the −50/+50 scale.
4 — Relative Balance : The reference values used in the calculation are the up and down EMAs used in the "Average Balance".
From those, we calculate two intermediate values using how much the instant up and down volumes on the bar exceed their respective EMA — but with a twist.
If the bar's up volume does not exceed the EMA of up volume, a zero value is used. The same goes for the down volume with the EMA of down volume.
Once we have our two intermediate values for the up and down volumes exceeding their respective MA, we subtract them. The final value is an ALMA of that subtraction.
The rationale behind using zero values when the bar's up/down volume does not exceed its EMA is to only take into account the more significant volume.
If both instant volume values exceed their MA, then the difference between the two is the signal's value.
The signal is called "relative" because the intermediate values are the difference between the instant up/down volumes and their respective MA.
This balance flatlines when the bar's up/down volumes do not exceed their EMAs, which makes it useful to spot areas where trader interest dwindles, such as consolidations.
The smaller the period of the final value's ALMA, the more easily it will flatline. These flat zones should be considered no-trade zones.
5 — Percent Balance : This balance is the ALMA of the ratio of the "Bar Balance" over the total volume for that bar.
From the balances and marker conditions, two more values are calculated:
1 — Marker Bias : This sums the up/down (+1/‒1) occurrences of the markers 1 to 4 over a period you define, so it ranges from −4 to +4, times the period.
Its calculation will depend on the modes used to calculate markers 3 and 4.
2 — Combined Balances : This is the sum of the bull/bear (+1/−1) states of each of the five balances, so it ranges from −5 to +5.
The periods for all of these balances can be configured in the "Periods" section at the bottom of the script's inputs. As you cannot see the balances on the chart, you can use my Volume Delta Columns Pro indicator in a pane; it can plot the same balances, so you will be able to analyze them.
Divergences
In the context of this indicator, a divergence is any bar where the bear/bull state of a balance (above/below its zero centerline) diverges from the polarity of a chart bar. No directional bias is assigned to divergences when they occur. Candle bodies and tops/bottoms can each be colored differently on divergences detected from distinct balances.
Divergence Channel
The divergence channel is the space between two levels (by default, the bar's open and close ) saved when divergences occur. When price (by default the close ) has breached a channel and a new divergence occurs, a new channel is created. Until that new channel is breached, bars where additional divergences occur will expand the channel's levels if the bar's price points are outside the channel.
Prices breaches of the divergence channel will change its state. Divergence channels can be in one of three different states:
• Bull (green): Price has breached the channel to the upside.
• Bear (red): Price has breached the channel to the downside.
• Neutral (gray): The channel has not yet been breached.
█ HOW TO USE THE INDICATOR
I do not make videos to explain how to use my indicators. I do, however, try hard to include in their description everything one needs to understand what they do. From there, it's up to you to explore and figure out if they can be useful in your trading practice. Communicating in videos what this description and the script's tooltips contain would make for very long videos that would likely exceed the attention span of most people who find this description too long. There is no quick way to understand an indicator such as this one because it uses many different concepts and has quite a bit of settings one can use to modify its visuals and behavior — thus how one uses it. I will happily answer questions on the inner workings of the indicator, but I do not answer questions like "How do I trade using this indicator?" A useful answer to that question would require an in-depth analysis of who you are, your trading methodology and objectives, which I do not have time for. I do not teach trading.
Start by loading the indicator on an active chart containing volume information. See here if you need help.
The default configuration displays:
• Normal candles where the bodies are only colored if the bar's volume has increased since the last bar.
If you want to use this indicator's candles, you may want to disable your chart's candles by clicking the eye icon to the right of the symbol's name in the top left of the chart.
• A top or bottom appended to the normal candles. It represents the difference between up and down volume for that bar
and is positioned at the top or bottom, depending on its polarity. If up volume is greater than down volume, a top is displayed. If down volume is greater, a bottom is plotted.
The size of tops and bottoms is determined by calculating a factor which is the proportion of volume delta over the bar's total volume.
That factor is then used to calculate the top or bottom size relative to a baseline of the average candle body size of the last 100 bars.
• An information box in the bottom right displaying intrabar and chart coverage information.
• A light red background when the intrabar volume differs from the chart's volume by more than 1%.
The script's inputs contain tooltips explaining most of the fields. I will not repeat them here. Following is a brief description of each section of the indicator's inputs which will give you an idea of what the indicator can do:
Normal Candles is where you configure the replacement candles plotted by the script. You can choose from different coloring schemes for their bodies and specify a unique color for bodies where a divergence calculated using the method you choose occurs.
Volume Tops & Botttoms is where you configure the display of tops and bottoms, and their EMAs. The EMAs are calculated from the high point of tops and the low point of bottoms. They can act as a channel to evaluate price, and you can choose to color the channel using a gradient reflecting the advances/declines in the balance of your choice.
Divergence Channel is where you set up the appearance and behavior of the divergence channel. These areas represent levels where price and volume delta information do not converge. They can be interpreted as regions with no clear direction from where one will look for breaches. You can configure the channel to take into account one or both types of divergences you have configured for candle bodies and tops/bottoms.
Background allows you to configure a gradient background color that reflects the advances/declines in the balance of your choice. You can use this to provide context to the volume delta values from bars. You can also control the background color displayed on volume discrepancies between the intrabar and the chart's timeframe.
Intrabars is where you choose the calculation mode determining the lower timeframe used to access intrabars. The indicator uses the chart's timeframe and the type of market you are on to calculate the lower timeframe. Your setting there should reflect which compromise you prefer between the precision of calculations and chart coverage. This is also where you control the display of the information box in the lower right corner of the chart.
Markers allows you to control the plotting of chart markers on different conditions. Their configuration determines when alerts generated from the indicator will fire. Note that in order to generate alerts from this script, they must be created from your chart. See this Help Center page to learn how. Only the last 500 markers will be visible on the chart, but this will not affect the generation of alerts.
Periods is where you configure the periods for the balances and the EMAs used in the indicator.
The raw values calculated by this script can be inspected using the Data Window.
█ INTERPRETATION
Rightly or wrongly, volume delta is considered by many a useful complement to the interpretation of price action. I use it extensively in an attempt to find convergence between my read of volume delta and price movement — not so much as a predictor of future price movement. No system or person can predict the future. Accordingly, I consider people who speak or act as if they know the future with certainty to be dangerous to themselves and others; they are charlatans, imprudent or blissfully ignorant.
I try to avoid elaborate volume delta interpretation schemes involving too many variables and prefer to keep things simple:
• Trends that have more chances of continuing should be accompanied by VD of the same polarity.
In trends, I am looking for "slow and steady". I work from the assumption that traders and systems often overreact, which translates into unproductive volatility.
Wild trends are more susceptible to overreactions.
• I prefer steady VD values over wildly increasing ones, as large VD increases often come with increased price volatility, which can backfire.
Large VD values caused by stopping volume will also often occur on trend reversals with abnormally high candles.
• Prices escaping divergence channels may be leading a trend in that direction, although there is no telling how long that trend will last; could be just a few bars or hundreds.
When price is in a channel, shifts in VD balances can sometimes give us an idea of the direction where price has the most chance of breaking.
• Dwindling VD will often indicate trend exhaustion and predate reversals by many bars, but the problem is that mere pauses in a trend will often produce the same behavior in VD.
I think it is too perilous to infer rigidly from VD decreases.
Divergence Channel
Here I have configured the divergence channels to be visible. First, I set the bodies to display divergences on the default Bar Balance. They are indicated by yellow bodies. Then I activated the divergence channels by choosing to draw levels on body divergences and checked the "Fill" checkbox to fill the channel with the same color as the levels. The divergence channel is best understood as a direction-less area from where a breach can be acted on if other variables converge with the breach's direction:
Tops and Bottoms EMAs
I find these EMAs rather interesting. They have no equivalent elsewhere, as they are calculated from the top and bottom values this indicator plots. The only similarity they have with volume-weighted MAs, including VWAP, is that they use price and volume. This indicator's Tops and Bottoms EMAs, however, use the price and volume delta. While the channel differs from other channels in how it is calculated, it can be used like others, as a baseline from which to evaluate price movement or, alternatively, as stop levels. Remember that you can change the period used for the EMAs in the "Periods" section of the inputs.
This chart shows the EMAs in action, filled with a gradient representing the advances/decline from the Momentum balance. Notice the anomaly in the chart's latest bars where the Momentum balance gradient has been indicating a bullish bias for some time, during which price was mostly below the EMAs. Price has just broken above the channel on positive VD. My interpretation of this situation would be that it is a risky opportunity for a long trade in the larger context where the market has been in a downtrend since the 5th. Intrepid traders choosing to enter here could do so with a "make or break" tight stop that will minimize their losses should the market continue its downtrend while hopefully preserving the potential upside of price continuing on the longer-term uptrend prevalent since the 28th:
█ NOTES
Volume
If you use indicators such as this one which depends on volume information, it is important to realize that the volume data they consume comes from data feeds, and that all data feeds are NOT created equally. Those who create the data feeds we use must make decisions concerning the nature of the transactions they tally and the way they are tallied in each feed, and these decisions affect the nature of our volume data. My Volume X-ray publication discusses some of the reasons why volume information from different timeframes, brokers/exchanges or sectors may vary considerably. I encourage you to read it. This indicator's display of a warning through a background color on volume discrepancies between the timeframe used to access intrabars and the chart's timeframe is an attempt to help you realize these variations in feeds. Don't take things for granted, and understand that the quality of a given feed's volume information affects the quality of the results this indicator calculates.
Markets as ecosystems
I believe it is perilous to think that behavioral patterns you discover in one market through the lens of this or any other indicator will necessarily port to other markets. While this may sometimes be the case, it will often not. Why is that? Because each market is its own ecosystem. As cities do, all markets share some common characteristics, but they also all have their idiosyncrasies. A proportion of a city's inhabitants is always composed of outsiders who come and go, but a core population of regulars and systems is usually the force that actually defines most of the city's observable characteristics. I believe markets work somewhat the same way; they may look the same, but if you live there for a while and pay attention, you will notice the idiosyncrasies. Some things that work in some markets will, accordingly, not work in others. Please keep that in mind when you draw conclusions.
On Up/Down or Buy/Sell Volume
Buying or selling volume are misnomers, as every unit of volume transacted is both bought and sold by two different traders. While this does not keep me from using the terms, there is no such thing as “buy only” or “sell only” volume. Trader lingo is riddled with peculiarities. Without access to order book information, traders work with the assumption that when price moves up during a bar, there was more buying pressure than selling pressure, just as when buy market orders take out limit ask orders in the order book at successively higher levels. The built-in volume indicator available on TradingView uses this logic to color the volume columns green or red. While this script’s calculations are more precise because it analyses intrabars to calculate its information, it uses pretty much the same imperfect logic. Until Pine scripts can have access to how much volume was transacted at the bid/ask prices, our volume delta calculations will remain a mere proxy.
Repainting
• The values calculated on the realtime bar will update as new information comes from the feed.
• Historical values may recalculate if the historical feed is updated or when calculations start from a new point in history.
• Markers and alerts will not repaint as they only occur on a bar's close. Keep this in mind when viewing markers on historical bars,
where one could understandably and incorrectly assume they appear at the bar's open.
To learn more about repainting, see the Pine Script™ User Manual's page on the subject .
Superfluity
In "The Bed of Procrustes", Nassim Nicholas Taleb writes: To bankrupt a fool, give him information . This indicator can display a lot of information. The inevitable adaptation period you will need to figure out how to use it should help you eliminate all the visuals you do not need. The more you eliminate, the easier it will be to focus on those that are the most useful to your trading practice. Don't be a fool.
█ THANKS
Thanks to alexgrover for his Dekidaka-Ashi indicator. His volume plots on candles were the inspiration for my top/bottom plots.
Kudos to PineCoders for their libraries. I use two of them in this script: Time and lower_tf .
The first versions of this script used functionality that I would not have known about were it not for these two guys:
— A guy called Kuan who commented on a Backtest Rookies presentation of their Volume Profile indicator.
— theheirophant , my partner in the exploration of the sometimes weird abysses of request.security() ’s behavior at lower timeframes.
PSESS1 - Learn PineScript InputsThis is a script written exclusively for people who are trying to learn Pine Script.
PSESS stands for "Pine Script Educational Script Series" which is a series of scripts that helps Pine Script programmers in 2 ways:
1. Learn Pine Script at more depth by an interactive environment where they can immediately see the effects of any change in the pre-written code and also comparing different lines code having tiny differences so they can grasp the details.
2. Have this script open while coding in order to copy the line they find useful
Pine Script Library couldn't be used for this purpose since this script has educational aspect and needs to be executable individually.
This is Script 1 of PSESS and focuses on inputs in Pine Script.
The script is densly commented in order to make it understandable. here is the outline of the script:
1. Inputs that can be received through the indicator() function
2. 12 possible types of input
3. Input() function arguments: defval - title - tooltip - inline - group - confirm
4. The different display of tooltip when inputs are inline
5. Multiple price and time inputs (on single request or multiple requests)
6. What happens when title argument is not specified
7. References and key points from them
Smart Money Concept Strategy - Uncle SamThis strategy combines concepts from two popular TradingView scripts:
Smart Money Concepts (SMC) : The strategy identifies key levels in the market (swing highs and lows) and draws trend lines to visualize potential breakouts. It uses volume analysis to gauge the strength of these breakouts.
Smart Money Breakouts : This part of the strategy incorporates the idea of "Smart Money" – institutional traders who often lead market movements. It looks for breakouts of established levels with significant volume, aiming to catch the beginning of new trends.
How the Strategy Works:
Identification of Key Levels: The script identifies swing highs and swing lows based on a user-defined lookback period. These levels are considered significant points where price has reversed in the past.
Drawing Trend Lines: Trend lines are drawn connecting these key levels, creating a visual representation of potential support and resistance zones.
Volume Analysis: The script analyzes the volume during the formation of these levels and during breakouts. Higher volume suggests stronger moves and increases the probability of a successful breakout.
Entry Conditions:
Long Entry: A long entry is triggered when the price breaks above a resistance line with significant volume, and the moving average trend filter (optional) is bullish.
Short Entry: A short entry is triggered when the price breaks below a support line with significant volume, and the moving average trend filter (optional) is bearish.
Exit Conditions:
Stop Loss: Customizable stop loss percentages are implemented to protect against adverse price movements.
Take Profit: Customizable take profit percentages are used to lock in profits.
Credits and Compliance:
This strategy is inspired by the concepts and code from "Smart Money Concepts (SMC) " and "Smart Money Breakouts ." I've adapted and combined elements of both scripts to create this strategy. Full credit is given to the original authors for their valuable contributions to the TradingView community.
To comply with TradingView's House Rules, I've made the following adjustments:
Clearly Stated Inspiration: The description explicitly mentions the original scripts and authors as the inspiration for this strategy.
No Direct Copying: The code has been modified and combined, not directly copied from the original scripts.
Educational Purpose: The primary purpose of this strategy is for learning and backtesting. It's not intended as financial advice.
Important Note:
This strategy is intended for educational and backtesting purposes only. It should not be used for live trading without thorough testing and understanding of the underlying concepts. Past performance is not indicative of future results.
A_Traders_Edge__LibraryLibrary "A_Traders_Edge__Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing Market Overview Scanners (MOS)
LabelLocation(_firstLocation)
This function is used when there's a desire to print an assets ALERT LABELS at a set location on the scale that will
NOT change throughout the progression of the script. This is created so that if a lot of alerts are triggered, they
will stay relatively visible and not overlap each other. Ex. If you set your '_firstLocation' parameter as 1, since
there are a max of 40 assets that can be scanned, the 1st asset's location is assigned the value in the '_firstLocation' parameter,
the 2nd asset's location is the (1st asset's location+1)...and so on. If your first location is set to 81 then
the 1st asset is 81 and 2nd is 82 and so on until the 40th location = 120(in this particular example).
Parameters:
_firstLocation (simple int) : (simple int)
Optional(starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 output variables each being a different location to print the labels so that an asset is asssigned to
a particular location on the scale. Regardless of if you have the maximum amount of assets being screened (40 max), this
function will output 40 locations… So there needs to be 40 variables assigned in the tuple in this function. What I
mean by that is you need to have 40 output location variables within your tuple (ie. between the ' ') regarless of
if your scanning 40 assets or not. If you only have 20 assets in your scripts input settings, then only the first 20
variables within the ' ' Will be assigned to a value location and the other 20 will be assigned 'NA', but their
variables still need to be present in the tuple.
SeparateTickerids(_string)
You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your MO scanner.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my MOS Scanner scripts:
assets = input.text_area(tIDset1, title="TickerID (MUST READ TOOLTIP)", tooltip="Accepts 40 TICKERID's for each
copy of the script on the chart. TEXT FORMATTING RULES FOR TICKERID'S:
(1) To exclude the EXCHANGE NAME in the Labels, de-select the next input option.
(2) MUST have a space (' ') AFTER each TickerID.
(3) Capitalization in the Labels will match cap of these TickerID's.
(4) If your asset has a BaseCurrency & QuoteCurrency (ie. ADAUSDT ) BUT you ONLY want Labels
to show BaseCurrency(ie.'ADA'), include a FORWARD SLASH ('/') between the Base & Quote (ie.'ADA/USDT')", display=display.none)
Returns: Returns 40 output variables of the different strings of TickerID's (ie. you need to output 40 variables within the
tuple ' ' regardless of if you were scanning using all possible (40) assets or not.
If your scanning for less than 40 assets, then once the variables are assigned to all of the tickerIDs, the rest
of the 40 variables in the tuple will be assigned "NA".
TickeridForLabelsAndSecurity(_includeExchange, _ticker)
This function accepts the TickerID Name as its parameter and produces a single string that will be used in all of your labels.
Parameters:
_includeExchange (simple bool) : (bool)
Optional(if parameter not included in function it defaults to false ).
Used to determine if the Exchange name will be included in all labels/triggers/alerts.
_ticker (simple string) : (string)
For this parameter, input the varible named '_coin' from your 'f_main()' function for this parameter. It is the raw
Ticker ID name that will be processed.
Returns: ( )
Returns 2 output variables:
1st ('_securityTickerid') is to be used in the 'request.security()' function as this string will contain everything
TV needs to pull the correct assets data.
2nd ('lblTicker') is to be used in all of the labels in your MOS as it will only contain what you want your labels
to show as determined by how the tickerID is formulated in the MOS's input.
InvalidTID(_tablePosition, _stackVertical, _close, _securityTickerid, _invalidArray)
This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
Parameters:
_tablePosition (simple string) : (string)
Optional(if parameter not included, it defaults to position.middle_right). Location on the chart you want the table printed.
Possible strings include: position.top_center, position.top_left, position.top_right, position.middle_center,
position.middle_left, position.middle_right, position.bottom_center, position.bottom_left, position.bottom_right.
_stackVertical (simple bool) : (bool)
Optional(if parameter not included, it defaults to true). All of the assets that are counted as INVALID will be
created in a list. If you want this list to be prited as a column then input 'true' here.
_close (float) : (float)
If you want them printed as a single row then input 'false' here.
This should be the closing value of each of the assets being tested to determine in the TickerID is valid or not.
_securityTickerid (string) : (string)
Throughout the entire charts updates, if a '_close' value is never regestered then the logic counts the asset as INVALID.
This will be the 1st TickerID varible (named _securityTickerid) outputted from the tuple of the TickeridForLabels()
function above this one.
_invalidArray (string ) : (array string)
Input the array from the original script that houses all of the invalidArray strings.
Returns: (na)
Returns a table with the screened assets Invalid TickerID's. Table draws automatically if any are Invalid, thus,
no output variable to deal with.
LabelSizes(_barCnt, _lblSzRfrnce)
This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your MOS includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the 'PrintedBarCount' function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') outputted by this function.
_lblSzRfrnce (string) : (string)
Optional(if parameter not included, it defaults to size.small). This will be the size of the 1st variable outputted
by this function ('assetNameLabel') BUT also affects the 2nd variable outputted by this function.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
AssetColor()
This function is used to assign 40 different colors to 40 variables to be used for the different labels/plots.
Returns: Returns 40 output variables each with a different color assigned to them to be used in your plots & labels.
Regardless of if you have the maximum amount of assets your scanning(40 max) or less,
this function will assign 40 colors to 40 variables that you have between the ' '.
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.
RCI(_rciLength, _source, _interval)
You will see me using this a lot. DEFINITELY my favorite oscillator to utilize for SO many different things from
timing entries/exits to determining trends.Calculation of this indicator based on Spearmans Correlation.
Parameters:
_rciLength (int) : (int)
Amount of bars back to use in RCI calculations.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional(if parameter not included, it defaults to 3). RCI calculation groups bars by this amount and then will.
rank these groups of bars.
Returns: (float)
Returns a single RCI value that will oscillates between -100 and +100.
RCIAVG(firstLength, _amtBtLengths, _rciSMAlen, _source, _interval)
20 RCI's are averaged together to get this RCI Avg (Rank Correlation Index Average). Each RCI (of the 20 total RCI)
has a progressively LARGER Lookback Length. Though the RCI Lengths are not individually adjustable,
there are 2 factors that ARE:
(1) the Lookback Length of the 1st RCI and
(2) the amount of values between one RCI's Lookback Length and the next.
*** If you set 'firstLength' to it's default of 200 and '_amtBtLengths' to it's default of 120 (aka AMOUNT BETWEEN LENGTHS=120)...
then RCI_2 Length=320, RCI_3 Length=440, RCI_4 Length=560, and so on.
Parameters:
firstLength (int) : (int)
Optional(if parameter is not included when the function is called, then it defaults to 200).
This parameter is the Lookback Length for the 1st RCI used in the RCI Avg.
_amtBtLengths (int) : (int)
Optional(if parameter not included when the function is called, then it defaults to 120).
This parameter is the value amount between each of the progressively larger lengths used for the 20 RCI's that
are averaged in the RCI Avg.
***** BEWARE ***** Too large of a value here will cause the calc to look back too far, causing an error(thus the value must be lowered)
_rciSMAlen (int) : (int)
Unlike the Single RCI Function, this function smooths out the end result using an SMA with a length value that is this parameter.
_source (float) : (float)
Source to use in RCI calculations (can use ANY source series. Ie, open,close,high,low,etc).
_interval (int) : (int)
Optional(if parameter not included, it defaults to 3). Within the RCI calculation, bars next to each other are grouped together
and then these groups are Ranked against each other. This parameter is the number of adjacent bars that are grouped together.
Returns: (float)
Returns a single RCI value that is the Avg of many RCI values that will oscillate between -100 and +100.
PercentChange(_startingValue, _endingValue)
This is a quick function to calculate how much % change has occurred between the '_startingValue' and the '_endingValue'
that you input into the function.
Parameters:
_startingValue (float) : (float)
The source value to START the % change calculation from.
_endingValue (float) : (float)
The source value to END the % change caluclation from.
Returns: Returns a single output being the % value between 0-100 (with trailing numbers behind a decimal). If you want only
a certain amount of numbers behind the decimal, this function needs to be put within a formatting function to do so.
Rescale(_source, _oldMin, _oldMax, _newMin, _newMax)
Rescales series with a known '_oldMin' & '_oldMax'. Use this when the scale of the '_source' to
rescale is known (bounded).
Parameters:
_source (float) : (float)
Source to be normalized.
_oldMin (int) : (float)
The known minimum of the '_source'.
_oldMax (int) : (float)
The known maximum of the '_source'.
_newMin (int) : (float)
What you want the NEW minimum of the '_source' to be.
_newMax (int) : (float)
What you want the NEW maximum of the '_source' to be.
Returns: Outputs your previously bounded '_source', but now the value will only move between the '_newMin' and '_newMax'
values you set in the variables.
Normalize_Historical(_source, _minimumLvl, _maximumLvl)
Normalizes '_source' that has a previously unknown min/max(unbounded) determining the max & min of the '_source'
FROM THE ENTIRE CHARTS HISTORY. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns your same '_source', but now the value will MOSTLY stay between the minimum and maximum values you set in the
'_minimumLvl' and '_maximumLvl' variables (ie. if the source you input is an RSI...the output is the same RSI value but
instead of moving between 0-100 it will move between the maxand min you set).
Normailize_Local(_source, _length, _minimumLvl, _maximumLvl)
Normalizes series with previously unknown min/max(unbounded). Much like the Normalize_Historical function above this one,
but rather than using the Highest/Lowest Values within the ENTIRE charts history, this on looks for the Highest/Lowest
values of '_source' within the last ___ bars (set by user as/in the '_length' parameter. ]
Parameters:
_source (float) : (float)
Source to be normalized.
_length (int) : (float)
The amount of bars to look back to determine the highest/lowest '_source' value.
_minimumLvl (int) : (float)
The Lower Boundary Level.
_maximumLvl (int) : (float)
The Upper Boundary Level.
Returns: Returns a single output variable being the previously unbounded '_source' that is now normalized and bound between
the values used for '_minimumLvl'/'_maximumLvl' of the '_source' within the user defined lookback period.
`security()` revisited [PineCoders]NOTE
The non-repainting technique in this publication that relies on bar states is now deprecated, as we have identified inconsistencies that undermine its credibility as a universal solution. The outputs that use the technique are still available for reference in this publication. However, we do not endorse its usage. See this publication for more information about the current best practices for requesting HTF data and why they work.
█ OVERVIEW
This script presents a new function to help coders use security() in both repainting and non-repainting modes. We revisit this often misunderstood and misused function, and explain its behavior in different contexts, in the hope of dispelling some of the coder lure surrounding it. The function is incredibly powerful, yet misused, it can become a dangerous WMD and an instrument of deception, for both coders and traders.
We will discuss:
• How to use our new `f_security()` function.
• The behavior of Pine code and security() on the three very different types of bars that make up any chart.
• Why what you see on a chart is a simulation, and should be taken with a grain of salt.
• Why we are presenting a new version of a function handling security() calls.
• Other topics of interest to coders using higher timeframe (HTF) data.
█ WARNING
We have tried to deliver a function that is simple to use and will, in non-repainting mode, produce reliable results for both experienced and novice coders. If you are a novice coder, stick to our recommendations to avoid getting into trouble, and DO NOT change our `f_security()` function when using it. Use `false` as the function's last argument and refrain from using your script at smaller timeframes than the chart's. To call our function to fetch a non-repainting value of close from the 1D timeframe, use:
f_security(_sym, _res, _src, _rep) => security(_sym, _res, _src )
previousDayClose = f_security(syminfo.tickerid, "D", close, false)
If that's all you're interested in, you are done.
If you choose to ignore our recommendation and use the function in repainting mode by changing the `false` in there for `true`, we sincerely hope you read the rest of our ramblings before you do so, to understand the consequences of your choice.
Let's now have a look at what security() is showing you. There is a lot to cover, so buckle up! But before we dig in, one last thing.
What is a chart?
A chart is a graphic representation of events that occur in markets. As any representation, it is not reality, but rather a model of reality. As Scott Page eloquently states in The Model Thinker : "All models are wrong; many are useful". Having in mind that both chart bars and plots on our charts are imperfect and incomplete renderings of what actually occurred in realtime markets puts us coders in a place from where we can better understand the nature of, and the causes underlying the inevitable compromises necessary to build the data series our code uses, and print chart bars.
Traders or coders complaining that charts do not reflect reality act like someone who would complain that the word "dog" is not a real dog. Let's recognize that we are dealing with models here, and try to understand them the best we can. Sure, models can be improved; TradingView is constantly improving the quality of the information displayed on charts, but charts nevertheless remain mere translations. Plots of data fetched through security() being modelized renderings of what occurs at higher timeframes, coders will build more useful and reliable tools for both themselves and traders if they endeavor to perfect their understanding of the abstractions they are working with. We hope this publication helps you in this pursuit.
█ FEATURES
This script's "Inputs" tab has four settings:
• Repaint : Determines whether the functions will use their repainting or non-repainting mode.
Note that the setting will not affect the behavior of the yellow plot, as it always repaints.
• Source : The source fetched by the security() calls.
• Timeframe : The timeframe used for the security() calls. If it is lower than the chart's timeframe, a warning appears.
• Show timeframe reminder : Displays a reminder of the timeframe after the last bar.
█ THE CHART
The chart shows two different pieces of information and we want to discuss other topics in this section, so we will be covering:
A — The type of chart bars we are looking at, indicated by the colored band at the top.
B — The plots resulting of calling security() with the close price in different ways.
C — Points of interest on the chart.
A — Chart bars
The colored band at the top shows the three types of bars that any chart on a live market will print. It is critical for coders to understand the important distinctions between each type of bar:
1 — Gray : Historical bars, which are bars that were already closed when the script was run on them.
2 — Red : Elapsed realtime bars, i.e., realtime bars that have run their course and closed.
The state of script calculations showing on those bars is that of the last time they were made, when the realtime bar closed.
3 — Green : The realtime bar. Only the rightmost bar on the chart can be the realtime bar at any given time, and only when the chart's market is active.
Refer to the Pine User Manual's Execution model page for a more detailed explanation of these types of bars.
B — Plots
The chart shows the result of letting our 5sec chart run for a few minutes with the following settings: "Repaint" = "On" (the default is "Off"), "Source" = `close` and "Timeframe" = 1min. The five lines plotted are the following. They have progressively thinner widths:
1 — Yellow : A normal, repainting security() call.
2 — Silver : Our recommended security() function.
3 — Fuchsia : Our recommended way of achieving the same result as our security() function, for cases when the source used is a function returning a tuple.
4 — White : The method we previously recommended in our MTF Selection Framework , which uses two distinct security() calls.
5 — Black : A lame attempt at fooling traders that MUST be avoided.
All lines except the first one in yellow will vary depending on the "Repaint" setting in the script's inputs. The first plot does not change because, contrary to all other plots, it contains no conditional code to adapt to repainting/no-repainting modes; it is a simple security() call showing its default behavior.
C — Points of interest on the chart
Historical bars do not show actual repainting behavior
To appreciate what a repainting security() call will plot in realtime, one must look at the realtime bar and at elapsed realtime bars, the bars where the top line is green or red on the chart at the top of this page. There you can see how the plots go up and down, following the close value of each successive chart bar making up a single bar of the higher timeframe. You would see the same behavior in "Replay" mode. In the realtime bar, the movement of repainting plots will vary with the source you are fetching: open will not move after a new timeframe opens, low and high will change when a new low or high are found, close will follow the last feed update. If you are fetching a value calculated by a function, it may also change on each update.
Now notice how different the plots are on historical bars. There, the plot shows the close of the previously completed timeframe for the whole duration of the current timeframe, until on its last bar the price updates to the current timeframe's close when it is confirmed (if the timeframe's last bar is missing, the plot will only update on the next timeframe's first bar). That last bar is the only one showing where the plot would end if that timeframe's bars had elapsed in realtime. If one doesn't understand this, one cannot properly visualize how his script will calculate in realtime when using repainting. Additionally, as published scripts typically show charts where the script has only run on historical bars, they are, in fact, misleading traders who will naturally assume the script will behave the same way on realtime bars.
Non-repainting plots are more accurate on historical bars
Now consider this chart, where we are using the same settings as on the chart used to publish this script, except that we have turned "Repainting" off this time:
The yellow line here is our reference, repainting line, so although repainting is turned off, it is still repainting, as expected. Because repainting is now off, however, plots on historical bars show the previous timeframe's close until the first bar of a new timeframe, at which point the plot updates. This correctly reflects the behavior of the script in the realtime bar, where because we are offsetting the series by one, we are always showing the previously calculated—and thus confirmed—higher timeframe value. This means that in realtime, we will only get the previous timeframe's values one bar after the timeframe's last bar has elapsed, at the open of the first bar of a new timeframe. Historical and elapsed realtime bars will not actually show this nuance because they reflect the state of calculations made on their close , but we can see the plot update on that bar nonetheless.
► This more accurate representation on historical bars of what will happen in the realtime bar is one of the two key reasons why using non-repainting data is preferable.
The other is that in realtime, your script will be using more reliable data and behave more consistently.
Misleading plots
Valiant attempts by coders to show non-repainting, higher timeframe data updating earlier than on our chart are futile. If updates occur one bar earlier because coders use the repainting version of the function, then so be it, but they must then also accept that their historical bars are not displaying information that is as accurate. Not informing script users of this is to mislead them. Coders should also be aware that if they choose to use repainting data in realtime, they are sacrificing reliability to speed and may be running a strategy that behaves very differently from the one they backtested, thus invalidating their tests.
When, however, coders make what are supposed to be non-repainting plots plot artificially early on historical bars, as in examples "c4" and "c5" of our script, they would want us to believe they have achieved the miracle of time travel. Our understanding of the current state of science dictates that for now, this is impossible. Using such techniques in scripts is plainly misleading, and public scripts using them will be moderated. We are coding trading tools here—not video games. Elementary ethics prescribe that we should not mislead traders, even if it means not being able to show sexy plots. As the great Feynman said: You should not fool the layman when you're talking as a scientist.
You can readily appreciate the fantasy plot of "c4", the thinnest line in black, by comparing its supposedly non-repainting behavior between historical bars and realtime bars. After updating—by miracle—as early as the wide yellow line that is repainting, it suddenly moves in a more realistic place when the script is running in realtime, in synch with our non-repainting lines. The "c5" version does not plot on the chart, but it displays in the Data Window. It is even worse than "c4" in that it also updates magically early on historical bars, but goes on to evaluate like the repainting yellow line in realtime, except one bar late.
Data Window
The Data Window shows the values of the chart's plots, then the values of both the inside and outside offsets used in our calculations, so you can see them change bar by bar. Notice their differences between historical and elapsed realtime bars, and the realtime bar itself. If you do not know about the Data Window, have a look at this essential tool for Pine coders in the Pine User Manual's page on Debugging . The conditional expressions used to calculate the offsets may seem tortuous but their objective is quite simple. When repainting is on, we use this form, so with no offset on all bars:
security(ticker, i_timeframe, i_source )
// which is equivalent to:
security(ticker, i_timeframe, i_source)
When repainting is off, we use two different and inverted offsets on historical bars and the realtime bar:
// Historical bars:
security(ticker, i_timeframe, i_source )
// Realtime bar (and thus, elapsed realtime bars):
security(ticker, i_timeframe, i_source )
The offsets in the first line show how we prevent repainting on historical bars without the need for the `lookahead` parameter. We use the value of the function call on the chart's previous bar. Since values between the repainting and non-repainting versions only differ on the timeframe's last bar, we can use the previous value so that the update only occurs on the timeframe's first bar, as it will in realtime when not repainting.
In the realtime bar, we use the second call, where the offsets are inverted. This is because if we used the first call in realtime, we would be fetching the value of the repainting function on the previous bar, so the close of the last bar. What we want, instead, is the data from the previous, higher timeframe bar , which has elapsed and is confirmed, and thus will not change throughout realtime bars, except on the first constituent chart bar belonging to a new higher timeframe.
After the offsets, the Data Window shows values for the `barstate.*` variables we use in our calculations.
█ NOTES
Why are we revisiting security() ?
For four reasons:
1 — We were seeing coders misuse our `f_secureSecurity()` function presented in How to avoid repainting when using security() .
Some novice coders were modifying the offset used with the history-referencing operator in the function, making it zero instead of one,
which to our horror, caused look-ahead bias when used with `lookahead = barmerge.lookahead_on`.
We wanted to present a safer function which avoids introducing the dreaded "lookahead" in the scripts of unsuspecting coders.
2 — The popularity of security() in screener-type scripts where coders need to use the full 40 calls allowed per script made us want to propose
a solid method of allowing coders to offer a repainting/no-repainting choice to their script users with only one security() call.
3 — We wanted to explain why some alternatives we see circulating are inadequate and produce misleading behavior.
4 — Our previous publication on security() focused on how to avoid repainting, yet many other considerations worthy of attention are not related to repainting.
Handling tuples
When sending function calls that return tuples with security() , our `f_security()` function will not work because Pine does not allow us to use the history-referencing operator with tuple return values. The solution is to integrate the inside offset to your function's arguments, use it to offset the results the function is returning, and then add the outside offset in a reassignment of the tuple variables, after security() returns its values to the script, as we do in our "c2" example.
Does it repaint?
We're pretty sure Wilder was not asked very often if RSI repainted. Why? Because it wasn't in fashion—and largely unnecessary—to ask that sort of question in the 80's. Many traders back then used daily charts only, and indicator values were calculated at the day's close, so everybody knew what they were getting. Additionally, indicator values were calculated by generally reputable outfits or traders themselves, so data was pretty reliable. Today, almost anybody can write a simple indicator, and the programming languages used to write them are complex enough for some coders lacking the caution, know-how or ethics of the best professional coders, to get in over their heads and produce code that does not work the way they think it does.
As we hope to have clearly demonstrated, traders do have legitimate cause to ask if MTF scripts repaint or not when authors do not specify it in their script's description.
► We recommend that authors always use our `f_security()` with `false` as the last argument to avoid repainting when fetching data dependent on OHLCV information. This is the only way to obtain reliable HTF data. If you want to offer users a choice, make non-repainting mode the default, so that if users choose repainting, it will be their responsibility. Non-repainting security() calls are also the only way for scripts to show historical behavior that matches the script's realtime behavior, so you are not misleading traders. Additionally, non-repainting HTF data is the only way that non-repainting alerts can be configured on MTF scripts, as users of MTF scripts cannot prevent their alerts from repainting by simply configuring them to trigger on the bar's close.
Data feeds
A chart at one timeframe is made up of multiple feeds that mesh seamlessly to form one chart. Historical bars can use one feed, and the realtime bar another, which brokers/exchanges can sometimes update retroactively so that elapsed realtime bars will reappear with very slight modifications when the browser's tab is refreshed. Intraday and daily chart prices also very often originate from different feeds supplied by brokers/exchanges. That is why security() calls at higher timeframes may be using a completely different feed than the chart, and explains why the daily high value, for example, can vary between timeframes. Volume information can also vary considerably between intraday and daily feeds in markets like stocks, because more volume information becomes available at the end of day. It is thus expected behavior—and not a bug—to see data variations between timeframes.
Another point to keep in mind concerning feeds it that when you are using a repainting security() plot in realtime, you will sometimes see discrepancies between its plot and the realtime bars. An artefact revealing these inconsistencies can be seen when security() plots sometimes skip a realtime chart bar during periods of high market activity. This occurs because of races between the chart and the security() feeds, which are being monitored by independent, concurrent processes. A blue arrow on the chart indicates such an occurrence. This is another cause of repainting, where realtime bar-building logic can produce different outcomes on one closing price. It is also another argument supporting our recommendation to use non-repainting data.
Alternatives
There is an alternative to using security() in some conditions. If all you need are OHLC prices of a higher timeframe, you can use a technique like the one Duyck demonstrates in his security free MTF example - JD script. It has the great advantage of displaying actual repainting values on historical bars, which mimic the code's behavior in the realtime bar—or at least on elapsed realtime bars, contrary to a repainting security() plot. It has the disadvantage of using the current chart's TF data feed prices, whereas higher timeframe data feeds may contain different and more reliable prices when they are compiled at the end of the day. In its current state, it also does not allow for a repainting/no-repainting choice.
When `lookahead` is useful
When retrieving non-price data, or in special cases, for experiments, it can be useful to use `lookahead`. One example is our Backtesting on Non-Standard Charts: Caution! script where we are fetching prices of standard chart bars from non-standard charts.
Warning users
Normal use of security() dictates that it only be used at timeframes equal to or higher than the chart's. To prevent users from inadvertently using your script in contexts where it will not produce expected behavior, it is good practice to warn them when their chart is on a higher timeframe than the one in the script's "Timeframe" field. Our `f_tfReminderAndErrorCheck()` function in this script does that. It can also print a reminder of the higher timeframe. It uses one security() call.
Intrabar timeframes
security() is not supported by TradingView when used with timeframes lower than the chart's. While it is still possible to use security() at intrabar timeframes, it then behaves differently. If no care is taken to send a function specifically written to handle the successive intrabars, security() will return the value of the last intrabar in the chart's timeframe, so the last 1H bar in the current 1D bar, if called at "60" from a "D" chart timeframe. If you are an advanced coder, see our FAQ entry on the techniques involved in processing intrabar timeframes. Using intrabar timeframes comes with important limitations, which you must understand and explain to traders if you choose to make scripts using the technique available to others. Special care should also be taken to thoroughly test this type of script. Novice coders should refrain from getting involved in this.
█ TERMINOLOGY
Timeframe
Timeframe , interval and resolution are all being used to name the concept of timeframe. We have, in the past, used "timeframe" and "resolution" more or less interchangeably. Recently, members from the Pine and PineCoders team have decided to settle on "timeframe", so from hereon we will be sticking to that term.
Multi-timeframe (MTF)
Some coders use "multi-timeframe" or "MTF" to name what are in fact "multi-period" calculations, as when they use MAs of progressively longer periods. We consider that a misleading use of "multi-timeframe", which should be reserved for code using calculations actually made from another timeframe's context and using security() , safe for scripts like Duyck's one mentioned earlier, or TradingView's Relative Volume at Time , which use a user-selected timeframe as an anchor to reset calculations. Calculations made at the chart's timeframe by varying the period of MAs or other rolling window calculations should be called "multi-period", and "MTF-anchored" could be used for scripts that reset calculations on timeframe boundaries.
Colophon
Our script was written using the PineCoders Coding Conventions for Pine .
The description was formatted using the techniques explained in the How We Write and Format Script Descriptions PineCoders publication.
Snippets were lifted from our MTF Selection Framework , then massaged to create the `f_tfReminderAndErrorCheck()` function.
█ THANKS
Thanks to apozdnyakov for his help with the innards of security() .
Thanks to bmistiaen for proofreading our description.
Look first. Then leap.
Waindrops [Makit0]█ OVERALL
Plot waindrops (custom volume profiles) on user defined periods, for each period you get high and low, it slices each period in half to get independent vwap, volume profile and the volume traded per price at each half.
It works on intraday charts only, up to 720m (12H). It can plot balanced or unbalanced waindrops, and volume profiles up to 24H sessions.
As example you can setup unbalanced periods to get independent volume profiles for the overnight and cash sessions on the futures market, or 24H periods to get the full session volume profile of EURUSD
The purpose of this indicator is twofold:
1 — from a Chartist point of view, to have an indicator which displays the volume in a more readable way
2 — from a Pine Coder point of view, to have an example of use for two very powerful tools on Pine Script:
• the recently updated drawing limit to 500 (from 50)
• the recently ability to use drawings arrays (lines and labels)
If you are new to Pine Script and you are learning how to code, I hope you read all the code and comments on this indicator, all is designed for you,
the variables and functions names, the sometimes too big explanations, the overall structure of the code, all is intended as an example on how to code
in Pine Script a specific indicator from a very good specification in form of white paper
If you wanna learn Pine Script form scratch just start HERE
In case you have any kind of problem with Pine Script please use some of the awesome resources at our disposal: USRMAN , REFMAN , AWESOMENESS , MAGIC
█ FEATURES
Waindrops are a different way of seeing the volume and price plotted in a chart, its a volume profile indicator where you can see the volume of each price level
plotted as a vertical histogram for each half of a custom period. By default the period is 60 so it plots an independent volume profile each 30m
You can think of each waindrop as an user defined candlestick or bar with four key values:
• high of the period
• low of the period
• left vwap (volume weighted average price of the first half period)
• right vwap (volume weighted average price of the second half period)
The waindrop can have 3 different colors (configurable by the user):
• GREEN: when the right vwap is higher than the left vwap (bullish sentiment )
• RED: when the right vwap is lower than the left vwap (bearish sentiment )
• BLUE: when the right vwap is equal than the left vwap ( neutral sentiment )
KEY FEATURES
• Help menu
• Custom periods
• Central bars
• Left/Right VWAPs
• Custom central bars and vwaps: color and pixels
• Highly configurable volume histogram: execution window, ticks, pixels, color, update frequency and fine tuning the neutral meaning
• Volume labels with custom size and color
• Tracking price dot to be able to see the current price when you hide your default candlesticks or bars
█ SETTINGS
Click here or set any impar period to see the HELP INFO : show the HELP INFO, if it is activated the indicator will not plot
PERIOD SIZE (max 2880 min) : waindrop size in minutes, default 60, max 2880 to allow the first half of a 48H period as a full session volume profile
BARS : show the central and vwap bars, default true
Central bars : show the central bars, default true
VWAP bars : show the left and right vwap bars, default true
Bars pixels : width of the bars in pixels, default 2
Bars color mode : bars color behavior
• BARS : gets the color from the 'Bars color' option on the settings panel
• HISTOGRAM : gets the color from the Bearish/Bullish/Neutral Histogram color options from the settings panel
Bars color : color for the central and vwap bars, default white
HISTOGRAM show the volume histogram, default true
Execution window (x24H) : last 24H periods where the volume funcionality will be plotted, default 5
Ticks per bar (max 50) : width in ticks of each histogram bar, default 2
Updates per period : number of times the histogram will update
• ONE : update at the last bar of the period
• TWO : update at the last bar of each half period
• FOUR : slice the period in 4 quarters and updates at the last bar of each of them
• EACH BAR : updates at the close of each bar
Pixels per bar : width in pixels of each histogram bar, default 4
Neutral Treshold (ticks) : delta in ticks between left and right vwaps to identify a waindrop as neutral, default 0
Bearish Histogram color : histogram color when right vwap is lower than left vwap, default red
Bullish Histogram color : histogram color when right vwap is higher than left vwap, default green
Neutral Histogram color : histogram color when the delta between right and left vwaps is equal or lower than the Neutral treshold, default blue
VOLUME LABELS : show volume labels
Volume labels color : color for the volume labels, default white
Volume Labels size : text size for the volume labels, choose between AUTO, TINY, SMALL, NORMAL or LARGE, default TINY
TRACK PRICE : show a yellow ball tracking the last price, default true
█ LIMITS
This indicator only works on intraday charts (minutes only) up to 12H (720m), the lower chart timeframe you can use is 1m
This indicator needs price, time and volume to work, it will not work on an index (there is no volume), the execution will not be allowed
The histogram (volume profile) can be plotted on 24H sessions as limit but you can plot several 24H sessions
█ ERRORS AND PERFORMANCE
Depending on the choosed settings, the script performance will be highly affected and it will experience errors
Two of the more common errors it can throw are:
• Calculation takes too long to execute
• Loop takes too long
The indicator performance is highly related to the underlying volatility (tick wise), the script takes each candlestick or bar and for each tick in it stores the price and volume, if the ticker in your chart has thousands and thousands of ticks per bar the indicator will throw an error for sure, it can not calculate in time such amount of ticks.
What all of that means? Simply put, this will throw error on the BITCOIN pair BTCUSD (high volatility with tick size 0.01) because it has too many ticks per bar, but lucky you it will work just fine on the futures contract BTC1! (tick size 5) because it has a lot less ticks per bar
There are some options you can fine tune to boost the script performance, the more demanding option in terms of resources consumption is Updates per period , by default is maxed out so lowering this setting will improve the performance in a high way.
If you wanna know more about how to improve the script performance, read the HELP INFO accessible from the settings panel
█ HOW-TO SETUP
The basic parameters to adjust are Period size , Ticks per bar and Pixels per bar
• Period size is the main setting, defines the waindrop size, to get a better looking histogram set bigger period and smaller chart timeframe
• Ticks per bar is the tricky one, adjust it differently for each underlying (ticker) volatility wise, for some you will need a low value, for others a high one.
To get a more accurate histogram set it as lower as you can (min value is 1)
• Pixels per bar allows you to adjust the width of each histogram bar, with it you can adjust the blank space between them or allow overlaping
You must play with these three parameters until you obtain the desired histogram: smoother, sharper, etc...
These are some of the different kind of charts you can setup thru the settings:
• Balanced Waindrops (default): charts with waindrops where the two halfs are of same size.
This is the default chart, just select a period (30m, 60m, 120m, 240m, pick your poison), adjust the histogram ticks and pixels and watch
• Unbalanced Waindrops: chart with waindrops where the two halfs are of different sizes.
Do you trade futures and want to plot a waindrop with the first half for the overnight session and the second half for the cash session? you got it;
just adjust the period to 1860 for any CME ticker (like ES1! for example) adjust the histogram ticks and pixels and watch
• Full Session Volume Profile: chart with waindrops where only the first half plots.
Do you use Volume profile to analize the market? Lucky you, now you can trick this one to plot it, just try a period of 780 on SPY, 2760 on ES1!, or 2880 on EURUSD
remember to adjust the histogram ticks and pixels for each underlying
• Only Bars: charts with only central and vwap bars plotted, simply deactivate the histogram and volume labels
• Only Histogram: charts with only the histogram plotted (volume profile charts), simply deactivate the bars and volume labels
• Only Volume: charts with only the raw volume numbers plotted, simply deactivate the bars and histogram
If you wanna know more about custom full session periods for different asset classes, read the HELP INFO accessible from the settings panel
EXAMPLES
Full Session Volume Profile on MES 5m chart:
Full Session Unbalanced Waindrop on MNQ 2m chart (left side Overnight session, right side Cash Session):
The following examples will have the exact same charts but on four different tickers representing a futures contract, a forex pair, an etf and a stock.
We are doing this to be able to see the different parameters we need for plotting the same kind of chart on different assets
The chart composition is as follows:
• Left side: Volume Labels chart (period 10)
• Upper Right side: Waindrops (period 60)
• Lower Right side: Full Session Volume Profile
The first example will specify the main parameters, the rest of the charts will have only the differences
MES :
• Left: Period size: 10, Bars: uncheck, Histogram: uncheck, Execution window: 1, Ticks per bar: 2, Updates per period: EACH BAR,
Pixels per bar: 4, Volume labels: check, Track price: check
• Upper Right: Period size: 60, Bars: check, Bars color mode: HISTOGRAM, Histogram: check, Execution window: 2, Ticks per bar: 2,
Updates per period: EACH BAR, Pixels per bar: 4, Volume labels: uncheck, Track price: check
• Lower Right: Period size: 2760, Bars: uncheck, Histogram: check, Execution window: 1, Ticks per bar: 1, Updates per period: EACH BAR,
Pixels per bar: 2, Volume labels: uncheck, Track price: check
EURUSD :
• Upper Right: Ticks per bar: 10
• Lower Right: Period size: 2880, Ticks per bar: 1, Pixels per bar: 1
SPY :
• Left: Ticks per bar: 3
• Upper Right: Ticks per bar: 5, Pixels per bar: 3
• Lower Right: Period size: 780, Ticks per bar: 2, Pixels per bar: 2
AAPL :
• Left: Ticks per bar: 2
• Upper Right: Ticks per bar: 6, Pixels per bar: 3
• Lower Right: Period size: 780, Ticks per bar: 1, Pixels per bar: 2
█ THANKS TO
PineCoders for all they do, all the tools and help they provide and their involvement in making a better community
scarf for the idea of coding a waindrops like indicator, I did not know something like that existed at all
All the Pine Coders, Pine Pros and Pine Wizards, people who share their work and knowledge for the sake of it and helping others, I'm very grateful indeed
I'm learning at each step of the way from you all, thanks for this awesome community;
Opensource and shared knowledge: this is the way! (said with canned voice from inside my helmet :D)
█ NOTE
This description was formatted following THIS guidelines
═════════════════════════════════════════════════════════════════════════
I sincerely hope you enjoy reading and using this work as much as I enjoyed developing it :D
GOOD LUCK AND HAPPY TRADING!
COMET_Scanner_Library_FINALLibrary "COMET_Scanner_Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing COM Scanners
TickerIDs(_string)
TickerIDs: You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your COM Scanner.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my COM Scanner scripts:
assets = input.text_area(tIDs, title="TickerIDs (MUST READ TOOLTIP)", group=g2, tooltip="Accepts 40 TICKERID's
for each copy of the script on the chart. \n\n*** MUST FORMAT THIS WAY ***\n\n Each FULL tickerID
(ie 'Exchange:ticker') must be separated by A SINGLE BLANK SPACE for correct formatting. The blank space tells
the script where to break off the ticker to assign it to a variable to be used later in the script. So this input
will be a single string constructed from up to 40 tickerID's with a space between each tickerID
(ie. 'BINANCE:BTCUSDT BINANCE:SXPUSDT BINANCE:XRPUSDT').", display=display.none)
Returns: Returns 40 output variables in the tuple (ie. between the ' ') with the separated TickerIDs,
Locations(_firstLocation)
Locations: This function is used when there's a desire to print an assets ALERT LABELS. A set Location on the scale is assigned to each asset.
This is created so that if a lot of alerts are triggered, they will stay relatively visible and not overlap each other.
If you set your '_firstLocation' parameter as 1, since there are a max of 40 assets that can be scanned, the 1st asset's location
is assigned the value in the '_firstLocation' parameter, the 2nd asset's location is the (1st asset's location+1)...and so on.
Parameters:
_firstLocation (simple int) : (simple int)
Optional (starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 variables for the locations for alert labels
LabelSize(_barCnt, _lblSzRfrnce)
INVALID TICKERIDs: This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
LABEL SIZES: This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your COM Scanner includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the Security function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') that is also outputted by this function.
_lblSzRfrnce (string) : (string)
Optional (if parameter not included, it defaults to size.small). This will be the size of the variable outputted
by this function named 'assetNameLabel' BUT also affects the size of the output variable 'alertTrigLabel' as it uses this parameter's size
as the smallest size for 'alertTrigLabel' then uses the '_barCnt' parameter to determine the next sizes up depending on the "_barCnt" value.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
InvalidTickerIDs(_close, _securityTickerid, _invalidArray, _tablePosition, _stackVertical)
Parameters:
_close (float)
_securityTickerid (string)
_invalidArray (array)
_tablePosition (simple string)
_stackVertical (simple bool)
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.
COM_Scanner_LibraryLibrary "COM_Scanner_Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing COM Scanners
TickerIDs(_string)
TickerIDs: You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your COM Scanner.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my COM Scanner scripts:
assets = input.text_area(tIDs, title="TickerIDs (MUST READ TOOLTIP)", group=g2, tooltip="Accepts 40 TICKERID's
for each copy of the script on the chart. \n\n*** MUST FORMAT THIS WAY ***\n\n Each FULL tickerID
(ie 'Exchange:ticker') must be separated by A SINGLE BLANK SPACE for correct formatting. The blank space tells
the script where to break off the ticker to assign it to a variable to be used later in the script. So this input
will be a single string constructed from up to 40 tickerID's with a space between each tickerID
(ie. 'BINANCE:BTCUSDT BINANCE:SXPUSDT BINANCE:XRPUSDT').", display=display.none)
Returns: Returns 40 output variables in the tuple (ie. between the ' ') with the separated TickerIDs,
Locations(_firstLocation)
Locations: This function is used when there's a desire to print an assets ALERT LABELS. A set Location on the scale is assigned to each asset.
This is created so that if a lot of alerts are triggered, they will stay relatively visible and not overlap each other.
If you set your '_firstLocation' parameter as 1, since there are a max of 40 assets that can be scanned, the 1st asset's location
is assigned the value in the '_firstLocation' parameter, the 2nd asset's location is the (1st asset's location+1)...and so on.
Parameters:
_firstLocation (simple int) : (simple int)
Optional (starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 variables for the locations for alert labels
LabelSize(_barCnt, _lblSzRfrnce)
INVALID TICKERIDs: This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
LABEL SIZES: This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your COM Scanner includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the Security function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') that is also outputted by this function.
_lblSzRfrnce (string) : (string)
Optional (if parameter not included, it defaults to size.small). This will be the size of the variable outputted
by this function named 'assetNameLabel' BUT also affects the size of the output variable 'alertTrigLabel' as it uses this parameter's size
as the smallest size for 'alertTrigLabel' then uses the '_barCnt' parameter to determine the next sizes up depending on the "_barCnt" value.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
InvalidTickerIDs(_close, _securityTickerid, _invalidArray, _tablePosition, _stackVertical)
Parameters:
_close (float)
_securityTickerid (string)
_invalidArray (array)
_tablePosition (simple string)
_stackVertical (simple bool)
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.